- Home /
instantiate within OnTriggerEnter, c# question.
Hi everyone,
Slowly trying to learn through the many examples and active Unity Community - getting a little stuck on something, though:
I want a player to hit an object and activate an instantiation that creates many more objects.
I did something to the extent of the following, but it is not working:
void OnTriggerEnter(Collider other) {
if (other.tag == "Player")
{
for (int i = 0; i < 200; i++)
{
Instantiate(prefab, new Vector3
(Random.Range(-50, 50), -324,
Random.Range(-50, 50)), Quaternion.identity);
prefab.transform.localScale = Vector3.one * Random.Range(-8f, 8f);
}
Any ideas?
maybe ....problem is on your component? 1.Did player Object tag on "Player"? 2.Did rigidbody setting is right?
Answer by SohailBukhari · May 28, 2018 at 06:31 AM
Make sure you pass the prefab in the inspector and also make sure that your OnTriggerEnter method working fine.
Make sure rigidbody added to the object which you are colliding. Check out this page: Unity Manual - Colliders Scroll to the bottom and look at the two tables. They show you what combinations of collider, trigger, rigidbody, isKinematic will collide together. Next, make sure the objects are not on collision layers that are set to ignore each other.
Also read this documentation https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
Thank you, Sohail. Since I am new, I don't yet trust when the problem is in the C# or in the Unity inspectors and menus. This helped me limit the number of possible errors and discover the flaw in my design.
This was the solution to my problem. I simply had to add a RigidBody element to the gameobject where the script was checking the ontriggerenter, and activated the Is Kinematic checkbox and it all worked. 4 years after your answer, it's still of use for people like me, thanks Sohail.