Change material of the player when enter a trigger
Hello everyone, I'm trying to create a script that changes the material of the player after he goes trough a trigger. I have a number of materials that I want to change randomly. My idea is similary to the gas stations form Need For Speed Most Wanted 2012. The problem is that the script doesn't do anything when I enter the trigger with that tag. Thanks! This is what I came up with:
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using UnityEngine; using Random = UnityEngine.Random;
public class ChangeColor : MonoBehaviour {
public Material[] material;
Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
int i = Random.Range(0, 6);
rend.sharedMaterial = material[i];
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "ColorChange")
{
int i = Random.Range(0, 4);
rend.sharedMaterial = material[i];
}
}
}
Answer by muckenhoupt · Aug 07, 2020 at 08:23 PM
The only thing I see wrong with the logic is that there's a chance that the material it picks will be the same as the one it already has. You might want to check for that and reroll when it happens.
But assuming that you aren't just having extremely bad luck with the RNG, it looks good to me. So I'm guessing that the problem isn't in the code, but in the objects. Check to see if OnTriggerEnter is getting called at all -- put in a breakpoint or a print statement or something. If it isn't, make sure that the trigger object really does have the ColorChange tag, that its isTrigger property is true, and that it has a RigidBody component.
If that's not the problem, then make sure that your materials array actually contains different materials!
Your answer
Follow this Question
Related Questions
How to get the Collider other element Rigidbody? 0 Answers
Object reference not set to an instance of an object 0 Answers
Change Scene with Physics Raycasting 1 Answer
Player Can Not get off platform 1 Answer
touch to activate animation 0 Answers