OnTriggerEnter called but variable is never set

2019-02-26 23:32发布

I've started learning Unity slowly using C# and it's been a blast thus far!

I've run into a small problem (I hope it's a small problem) and gotten stuck, and have been somewhat questioning my sanity ever since.

In my main script which runs first I have code that generates a primitive (sphere) on the fly and attaches a script to it, the scrip checks to see if the sphere has been triggered.

Main script

bool createNav (Vector3 _start) {

        GameObject nav = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        nav.AddComponent<NavTrigger>();

        nav.collider.isTrigger = true;

        nav.transform.localScale = new Vector3(1f,1f,1f);
        nav.transform.position = _start;

        return nav.GetComponent<NavTrigger>().Triggered;
    }

My other script

private bool triggered = false;

    void OnTriggerEnter() {

        this.triggered = true;
    }

    public bool Triggered {

        get { return this.triggered; }
    }

Sadly, it still returns false regardless of it running the OnTriggerEnter code.

Please, if anyone has any ideas or suggestions at all let me know I will try and do just about anything to make this work.

Thank you very much for your help! :)

标签: unity3d
1条回答
The star\"
2楼-- · 2019-02-26 23:53

OnTriggerEnter requires a parameter (Collider other) or it won't match the signature Unity expects.

private bool triggered = false;

    void OnTriggerEnter(Collider other) {
        Debug.Log("Triggered");
        this.triggered = true;
    }

    public bool Triggered {

        get { return this.triggered; }
    }
}

Also, as the documentation states:

Note that trigger events are only sent if one of the colliders also has a rigid body attached.

查看更多
登录 后发表回答