Create GameObject on Event

Hi,

I want to create a particle system at the current camera position every time a certain button is pressed. So I have the according game object of the particle system (in my scene) and made a prefab out of it.

When the button is pressed I instantiate the object
at the current position - works fine.

Now the thing is that I do not want to show the object before the button is pressed, which is the case since it is a game object.

How can I solve this?
When I remove it from the scene (keeping the prefab) it cant be instantiated on button pressed (Null-reference) either.

Thanks

Ok. I have managed to instantiate a prefab on an event, without it being in the scene as a game object.

Now the problem is that I want a script to be attached to the prefab.

What I want: a particle ball being shooted on each (specified) event and as soon as it hits an object instantiate (for once) another particle system.

So the particle ball is my prefab. The script assigned to the according GameObject makes it move along the camera direction and stop moving when it hits an object. Furthermore the script instantiates the other particle system (if not yet created).

But I think it is not possible to attach a script to a prefab, so what would be a good solution?

Thanks.

I have worked around this by storing all bullets in a list. So on each update I update the position of all bullets in the list.

If theres a better way I d be happy to know.

There’s no reason you can’t attach a script to a prefab, you just have to add your script to its GameObject. If adding the script breaks the prefab connection, just recreate the prefab after attaching the script.

Yes, but I couldnt find a way to attach a script to a GameObject that is created on an event (that is initially not placed in the scene).

So then the question would be: how can I dynamically attach a script to a GameObject on its creation?

If the script is attached to the prefab then when you instantiate the object it will already have the script attached.

But to answer your question, you can add scripts to objects at runtime with AddComponent like so:

var bulletPrefab : GameObject;
var newPosition : Vector3;

var newBullet = Instantiate(bulletPrefab, newPosition, Quaternion.identity);

var script : BulletScript = newBullet.AddComponent(BulletScript);

script.DoStuff();

Excellent, thats what I wanted to know.

Thank you!