Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

FindObjectOfType

Discussion in 'Scripting' started by bdoom, Apr 26, 2015.

  1. bdoom

    bdoom

    Joined:
    Apr 13, 2013
    Posts:
    12
    So in the game I'm making I have multiple characters. Each enemy unit spawns a prefab instance of a "bullet" sprite and it happens every .5 seconds. Now, my problem is, when the character hits the edge of a platform he turns around, and the x scale is flipped as well. The problem isn't the flipping but instead "FindObjectOfType<EnemyController>()" is finding the first enemy with the script "enemycontroller" attached to them. So basically when the first enemy flips, the bullets of the other guy are all flipped in the wrong direction. When one guy flips, the spawn point is changed. I'll attach pictures to make sense of this all.

    If you notice the first "thugBomb" prefab spawns and it is attached to "thug 1"

    Now in the second one, which is for the other enemy it's STILL ATTACHED TO THUG 1!!!




    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class thugBulletController : MonoBehaviour {
    5.  
    6.     public float speed;
    7.     public ThugController thug;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.      
    12.         thug = FindObjectOfType<ThugController>();
    13.  
    14.         if (thug.transform.localScale.x < 0)
    15.             speed = -speed;
    16.  
    17.  
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update () {
    22.         GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
    23.     }
    24.  
    25.  
    26.  
    27.  
    28.  
    29. }
    30.  
    Basically I'm trying to figure out how to make the code know which "thug" spawned the object so that it doesn't wrongfully set the direction of the bullet.
     
  2. bdoom

    bdoom

    Joined:
    Apr 13, 2013
    Posts:
    12
    Nevermind I found out how to fix this. I ended up editing where I instansiate the prefab and use the "SendMessage" function to send the name of the game object to the bullet controller script. This way the bullet will know which object it is supposed to be listening to.