简体   繁体   中英

Unity C# GameObject collides with another GameObject

I have a invicible GameObject called trigger, and when my Hero collides with it, a chandelier falls. I want to give the chandelier a Rigidbody so it falls, and you can collide with it and maybe use it.

If you can explain to me how collision works and show how to do something if to gameObject collides its would realy cool still new at Unity.

using UnityEngine;
using System.Collections;

public class Collider : MonoBehaviour {
    public GameObject chandelier;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    //When my hero collides with trigger go to the fall function
    void OnTriggerEnter (Collider other) {

        if (other.tag == "Trigger")
        {
            fall(); 
        }
    }

    //Add Rigidbody to the GameObject called chandelier
    void fall ()
    {
        chandelier.rigidbody.AddForce(1, 1, 1);
    }
}

For collision to work at least one of your colliding gameObjects must have a rigidbody attached to it, since you using OnTriggerEnter method, the following setup should work:

First object:

-collider (Marked as trigger)

-rigidbody (Marked as kinematic)

Second object

-collider (Marked as trigger)

Then when the objects collide, "OnTriggerEnter" method will get called and you can add the physical rigidbody to the second object, please notice that you cannot add a rigid body as you mentioned in your post

// This will cause to Exception if there is no rigidbody attached
chandelier.rigidbody.AddForce(1,1,1);

So basically you have to options:

-Add a rigidbody to your game object through Unity editor and set it to kinematic, then remove "Is kinematic" flag in your collision method, like this:

rigidbody.isKinematic = false;

-Add the rigidbody after collision using the following code:

gameObject.AddComponent< Rigidbody >();

Afterwards you can add the required force or if you only want it to fall, simply add gravity to the rigidbody:

rigidbody.useGravity = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM