Finding Objects in Script

I’m trying to add a health power-up, I can add it as a public game object then replace it via unity interface (and I tried it, worked) but I want to find object inside script.

There is no issue in spawning health’s after enemy death, I’m generating a random value and if it’s same with another value (initially entered) it spawns a health:: (if random.range(1,10)==5) like this. I embedded a script in health so I know it’s reacting when touches player. In playerController script I have this code:

GameObject health;

void Start()
{
health = GameObject.Find (“health”);
}

void OnTriggerEnter2D (Collider2D thing)
{

  hitFire missile = thing.gameObject.GetComponent<hitFire> ();


  if (missile)
  {
  	playerHealth -= 1;
  }
  if(health)
  {
  	playerHealth += 1;
  }

}

Hi Muhammed,

Take a look at the link below regarding Object.FindObjectOfType<> (and the other one regarding how to format your code in your posts :wink: )

Note that any find methods are often costly from a performance perspective, as all GameObjects within the scene have to be checked. You may find an alternative approach more beneficial, perhaps by instantiating your health power-up and maintaining a reference to it as an object, you could then just access this within your script(s). By doing so you remove the need to find it at all.


See also;

Privacy & Terms