Search code examples
c#canvasunity-game-enginecollision

Show Canvas by trigger in Unity3d


I have a scene with two cubes, and canvas. One cube falls onto another. Canvas appearing must be triggered by collision. It's does not working. Where's the problem?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class EverythingInside : MonoBehaviour
{

public Canvas GUICanvas;
void Start()
{
}
void OnGUI()
{
    GUICanvas.gameObject.SetActive(true);
}
void OnCollisionEnter(Collision col)
{
    if (col.gameObject.tag == "FallingCube")
    {
        OnGUI();
    }
}
void Update()
{
}

}

Solution

  • Put the code below inside your EverythingInside script. Make sure Collider and Rigidbody are attached to both cubes. Also make sure to drag your Canvas from the Editor to the GUICanvas slot.

    public Canvas GUICanvas;
    
    void Start()
    {
    
    }
    
    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.CompareTag("FallingCube"))
        {
            GUICanvas.gameObject.SetActive(true);
        }
    }
    
    void Update()
    {
    
    }
    

    Unity Physics tutorials.

    Unity UI Tutorials.

    Unity Scripting Tutorials.