How can i define a costume function for an object in a prefub that I spawn?
I'm new to Unity, and my background in coding is mostly scientific programming/scripting so please be gentle.
I have a prefab called guy
that has a script file attached to it. This script file has a function, test
defined as
void test(){
//boring, I know, later this will actually do something
Debug.Log("Test");
Debug.Break();
}
I spawn guy
when player
is created (in player.Start()
and I want guy
to be stored inside of it. This is what I do
public GameObject guy;
void Start(){
//Some stuff happen before, but this is the part where I create guy
GameObject myguy = (GameObject)Instantiate(guy, new Vector3(1,1,1), Quaternion.identity)
myguy.test()
}
But I get an error saying UnityEngine.GameObject' does not contain a defi nition for `test' and no extension method `test' of type `UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?
I believe I should cast the Instantiate product into my prefab object, but I can'f find out how.
What am I doing wrong?
Answer by doublemax · Oct 12, 2016 at 04:08 PM
GameObject go = (GameObject)Instantiate(guy, new Vector3(1,1,1), Quaternion.identity);
GuyScript myguy = go.GetComponent<GuyScript>();
myguy.test()
Replace "GuyScript" with the name of the script/class attached to the prefab.
Your answer
Follow this Question
Related Questions
Instantiating prefab causes existing instances to change values 1 Answer
Spawn Prefab on double touch 2 Answers
Problem Instantiating a Prefab 1 Answer
Change serialize field input 0 Answers