Can't modify attributes of a component attached to a ParticleSystem after Instantiate?

I’m stumped, on something that seems pretty basic. I am really hoping someone can spot my mistake.

I am trying to instantiate prefab ParticleSystems at runtime and then modify the attributes of another component attached to the prefab, but those changed attributes don’t seem to “stick”. Allow me to elaborate on the process I’m going through:

  1. Create a new particle system. For simplicity, assume the particle system is set up to emit a single particle. It is set up for Collision and to send collision messages, and to collide with my player.

  2. Below the particle system component in the inspector, I “Add component” and choose a simple script that has details that I want to ‘travel’ with the particle. It has a public int called particleValue which has a default value of 0.

  3. Now I create a prefab from that object by dragging it to my project.

  4. At run time, from another script, I instantiate one of these prefabs by calling Instantiate:

GameObject gob = Instantiate(thePrefab,…);

  1. Then I get the component attached to the prefab:

MyHandler params = gob.GetComponent();

  1. And then I set a value in that component:

params.particleValue = 42;

and in my MyHandler script, I have

void OnParticleCollision(GameObject whatDidWeHit)
{
if(whatDidWeHit.CompareTag(“Player”)
Debug.Log("The particle collided with the player and has a particleValue= " + particleValue);
}

When I run this code, I get the collision message as expected, but the value it prints out is always the default (0) not the value set at runtime (42). Any idea what I am doing wrong? Seems like I’m modifying the value of the instantiated object (gob) not the prefab, so why doesn’t it “remember” the value set after instantiation?

This problem seems to only occur on ParticleSystem prefabs - I have a lot of other gameobjects that are instantiated at runtime and I can modify their parameters just fine. Is there something special about ParticleSystem that I don’t understand?

Ok, so after hours of head scratching, once I posted my question I almost immediately found my mistake (figures). The problem was, I was setting particleValue to the default in the Start() method for my handler, and that apparently gets called after I was finished with the Instantiate procedure where I was setting it at runtime, so therefore it would always get put back to the default. I keep thinking of Start() as a constructor, which is obviously wrong on my part.

1 Like

You can use Awake for such purposes. It will be called on instantiation, i.e. it’ll have executed even before you can access the instantiated object for the first time.

More specifically - Awake is called immediately after your Instantiate call. Start is called in the next frame.