Search Unity

One script for all canvas and triggers

Discussion in 'Scripting' started by cruising, Jul 5, 2015.

  1. cruising

    cruising

    Joined:
    Nov 22, 2013
    Posts:
    329
    Hello!

    I have a problem that idk how to solve.

    I have 2 triggers (for now), 1 script that looking for "Canvas" on start.
    I add the script to both triggers,i assing the right canvas for the right trigger.

    Now when i enter trigger 1 or 2, the same button shows up allways. The trigger should only show the canvas that are assigned to it self, or am i doing this wrong?

    CODE:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class LoadSceneButton : MonoBehaviour {
    5.    
    6.     public Canvas Canvas; //the canvas to be shown
    7.  
    8.     void Start () {
    9.  
    10.         GameObject go = GameObject.Find("Canvas");
    11.         if (!go)
    12.             return;
    13.        
    14.         Canvas = go.GetComponent<Canvas>();
    15.        
    16.         if (Canvas)
    17.             Canvas.enabled = false;
    18.    
    19.     }
    20.  
    21.     void OnTriggerEnter (Collider other )
    22.     {
    23.         if( other.tag == "Player" )
    24.         {
    25.             Canvas.enabled = true; //Show the public Canvas
    26.     }
    27. }
    28.  
    29.  
    30.     void OnTriggerExit (Collider other)
    31.     {
    32.         if( other.tag == "Player" )
    33.         {
    34.             Canvas.enabled = false; // Dont show the public Canvas
    35.         }
    36.     }
    37. }
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,261
    You are assigning the Canvas through the editor and you still look for it and assign it in Start overriding what you have assigned in the editor.
     
  3. cruising

    cruising

    Joined:
    Nov 22, 2013
    Posts:
    329
    Should i remove what i have in "void start" ?
     
  4. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,261
    You don't need what you have in Start so you need to remove it. I usually do error checking to make sure that Canvas has been assigned.

    Something like:
    Code (CSharp):
    1. void Start()
    2. {
    3.     if (!Canvas)
    4.         throw new UnityException("Canvas has not been assigned!");
    5. }
    Edit:
    One thing I want to point out is your naming. I would avoid naming a value the same as its class as it can cause problems and confusion later on down the road, making the debug process a lot harder.
     
    Last edited: Jul 6, 2015
  5. cruising

    cruising

    Joined:
    Nov 22, 2013
    Posts:
    329

    Thanks for your help, it works as it should do now!