3

I am trying to access a script on another gameobject that is instantiated in my script, and no matter what I do the script always returns null.

I instantiate the gameobject first by doing this.

asteroid = (GameObject)Instantiate(asteroidPrefab);

after that I try acessing its script by doing this:

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent(typeof(AsteroidHandler));

To check whether or not the handler was set properly I did this:

if(handler == null){
    Debug.Log("Asteroid Handler is Null");
}else{
    Debug.Log("Asteroid Handler was setup properly");
}

The problem is this always does the null option. I have the AsteroidHandler script attached to the asteroidPrefab prefab, and when I Instantiate it, it Instantiates properly, as I see the asteroid on the screen. Still when I try accessing the AsteroidHandler script that is attatched to it, it seems to act like it isn't there;

I have tried a couple other methods to access AsteroidHandler but they all say its null:

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent<AsteroidHandler>();

.

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent(typeof(AsteroidHandler)) as Asteroid Handler;

I have looked at a couple other questions similar to mine, but none of the answers seem to help.

Any help would be appreciated.

Bhaskar
  • 680
  • 7
  • 26

1 Answers1

4

Couldn't be easier,

add this code

asteroid = (GameObject)Instantiate(asteroidPrefab);
// add this...
asteroid.name = "Added test item";

run the program and wait until you see the "Added test item"

Check, do you ALSO see the "Asteroid Handler is Null"

Now, literally look in your Heirarchy for the scene, and find the object named Added test item

Look carefully at the Inspector, see what you see.

Fattie
  • 27,874
  • 70
  • 431
  • 719
  • ugh I am so stupid. When I did this, the object that was changed to "Added test item" was another object. Basically the prefab I put in for the asteroidPrefab in the unity editor wasn't the right prefab so it didn't have the script in it. This definitely seems like a good way to test if your instantiated object has instantiated properly and that it is the right object XD. Thank you, and I'm sorry for wasting your time with such a stupid problem. – Bhaskar Jul 03 '16 at 14:41
  • You're hardly stupid, you're clearly a naturally talented developer, **since the first thing you did was add a Debug.Log line** as you mention. Outstanding! That's the mark of excellence. Cheers! – Fattie Jul 03 '16 at 14:44
  • If you are new to Unity, here's an incredibly useful post http://stackoverflow.com/questions/35890932/unity-game-manager-script-works-only-one-time/35891919#35891919 – Fattie Jul 03 '16 at 14:44