- Home /
Accessing script variables of instantiaded prefab
Hi guys. This is one of my largest problems - I never know how to access specific parts of my object, and it seems that every time I have to use a different method. I am posting my current problem here, but would be glad to receive a longer explanation of this component hierarchy.
My code: A spawner object spawns a prefab from a prefab array. (this works fine)
Transform enemy = Instantiate (prefabs[size],transform.position,
Quaternion.identity) as Transform;
Afterwards I want to set some attributes of the instantiated prefab. All of the prefabs have the same script attached "Enemy.cs"
public class Enemy : MonoBehaviour {
public Attributes attributes;
}
[System.Serializable]
public class Attributes
{
public float xSpeed = 10;
public float ySpeed = 10;
public float size =0;
}
The way I set the atributes is by creating a new object of Atribute class and assigning it to the script. There is a function in spawner that returns a randomly generated attribute object. So what I am trying to do in code looks like this:
Enemy enemyScript = enemy.gameObject.GetComponent<Enemy>();
enemyScript.attributes = MakeRandomAttributes ();
The first line of this part throws an error. (Object reference not set to an instance of the object). I did something similar witha bit different architecture and something similar worked fine.
What am I doing wrong? What is the difference between GameObject and Transform?
I don't see anything immediately wrong with your script. So, to be clear, is there anything that comes between:
Transform enemy = Instantiate (prefabs[size],transform.position,
Quaternion.identity) as Transform;
and
Enemy enemyScript = enemy.gameObject.GetComponent<Enemy>();
?
Answer by wolis · Aug 10, 2014 at 02:07 PM
Found the solution to problem, appearantly, you cant store your instantiated prefab as a Transform, if you intend to access its scripts. Read more here: http://answers.unity3d.com/questions/237806/instantiate-not-returning-anything.html
Your answer
Follow this Question
Related Questions
GetComponent of ALL clones? 2 Answers
Weird GetComponent error 2 Answers
Reference Not Set toInstance of Object 1 Answer
GetComponent not Returning 1 Answer
What is the difference between GameObject.GetComponent and Component.GetComponent? 1 Answer