Enabling a component when hitting a trigger.

So I have a game where I shoot a bubble to try and get gems by bouncing it off obstacles. One of the side objects is to also collect coins which enable bonus things to be unlocked in a shop, and I want to add a visual reward for getting the coin. The way I want to do this is to enabled a trail renderer once it hits the coin which is a trigger. I have the trail renderer added as a component to the bubble but unchecked. I then have this code

function OnTriggerEnter (col : Collider){
	Destroy (col.gameObject);	//destroy the coin
	bubble = GameObject.findWithTag("Bubble");
	foreach (Component c in bubble.GetComponentsInChildren(typeof(Renderer)))

  if(c.name.Contains("Trail"))

    TrailRenderer.renderer.enabled = true;
}

attached as a scrip to the bubble to enable the trail renderer once it hits the coin. The coin being the only trigger for the moment. The coin destruction part works, but I can’t seem to get enabling trail renderer part to work. Any help on how to code it correctly are appreciated. Thanks in advance.

Not sure if I got the question right, or if this is the problem. But I think the problem with your code is this:

if(c.name.Contains("Trail"))

TrailRenderer.renderer.enabled = true

If you want to use an if-statement without {} you need to make sure that the stuff you want to happens is directly underneath the if. Like this:

if(c.name.Contains("Trail"))
TrailRenderer.renderer.enabled = true

;

If that does not work, post again and I can have another look.

I don’t know what the foreach is for in your code…

Can’t you just do:

bubble.GetComponent(TrailRenderer).enabled = true;
1 Like

I changed it to this, but it still doesn’t work.

function OnTriggerEnter (col : Collider){
	Destroy (col.gameObject);	//destroy the coin
	bubble = GameObject.findWithTag("Bubble");
	bubble.GetComponent(TrailRenderer).enabled = true;
}

As its not failing when getting the component I will assume that is happening correctly and I take it that the bubble is moving to create the trail

Maybe post a shot of the inspector view on this gameobject so we can see if a setting is wrong

here are screenshots of the inspector view.



and two more.


Nothing seems to be jumping out as wrong looking at your inspector … I even made a quick project with similar setup and it worked fine

1632035–100544–$New Unity Project.zip (132 KB)

1 Like

How would I do this

m_trail = GetComponent<TrailRenderer>();

in javascript?