Call a Function when Object Created

Hello Everybody,

I have a "Uret Function" this function's task is print i values to console how can i call and start this function when i create a object? I want this function will start working when i create a cube?

var Object : GameObject;
var i : int;

function Uret()
    while (i < 6) 
                yield WaitForSeconds (5);

Thank you for your help



To invoke functionality on a MonoBehaviour after instantiation use the Awake or Start methods. These have distinct implications but both get called after Unity creates the object. These are documented here.

var scriptInstance = Instantiate(myPrefab).GetComponent(ScriptName);

Sorry for the super necro, I’m wanting to do this in a newer version of Unity, and I’m having an issue.
This is how I’m creating my prefab during runtime.

GameObject NewBloodSpurt = Instantiate(BloodSpurtObj, hit.point, this.transform.rotation);

Now I would “think” that doing this would work, but it gives an error, saying “BloodSquirt” doesn’t exist in this context. Well yeah, the prefab hasn’t been created yet, but the prefab instance NewBloodSpurt will have the BloodSquirt script on it, so it should be able to access it, right?


I tried the method above given by Eric5h5, and it doesn’t work. I love the simplicity of it, and would love something similar. When I do it, it still says that the “BloodSquirt” script doesn’t exist in the current context. Here’s my attempt.

var scriptInstance = Instantiate(BloodSpurtObj).GetComponent(BloodSquirt);

Basically, I want to create an instance of a prefab, and then call a function in that prefab immediately. The reason I don’t want to use start() is because I need to send the tag information into the function.

Put the script on the cube and call the method from Start.