- Home /
The question is answered, right answer was accepted
How to call a function on an instance
On my playerScript, when i press spacebar, the function "PlantBomb" is called. This instantiates the "bomb" prefab. I'd like to run a function of bombScript (the script of bomb), and pass it a variable, letting it know how long to wait before exploding. The only error i'm getting, is the line that has bombTimer on it. It's bombTimer is red, like it doesn't know what the function is. This function exists on the bombScript though. Any help?
public GameObject bomb;
void PlantBomb () {
var bombClone = (GameObject)Instantiate (bomb, transform.position, transform.rotation) as GameObject;
bombClone.GetComponent<bombScript>.bombTimer (5);
}
if (Input.GetKeyDown(KeyCode.Space))
{
PlantBomb ();
}
Is this C# or UnityScript? Is that second block in Update() or what? Functions often have uppercase names are you sure it's bombTimer function and not BombTimer?
Answer by Mmmpies · Feb 07, 2015 at 07:25 PM
If C# try this:
bombClone.GetComponent<bombScript>().bombTimer (5);
Thanks mmpies, that was it! Also i realised i needed to make the bombTimer function public in the bombScript.
No problem @Biggidybigz see this is your first question, if it's the right answer it's a good idea to tick it correct, it shows people looking for the same thing that it's answered, stops others from looking at it to fix, gives me some karma points and means anyone looking at your profile that you tick the answers. If you get a reputation for not ticking the correct answer then some people don't bother looking at your questions.
You can even tick your own answer if you find a fix yourself. Best practice is tick the best or first answer if all similar. e.g. One of my questions no one knew the answer, I worked out a work around and ticked my own fix. Couple of weeks later someone came up with a much better way so I un-ticked my answer and ticked theirs.
Hey glad it worked though.