Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Access a GameObject Script

Discussion in 'Scripting' started by AzoR725, Feb 17, 2018.

  1. AzoR725

    AzoR725

    Joined:
    Feb 17, 2018
    Posts:
    3
    My code actually work but it is very unaesthetic, basically every time i need to get the value from the reference script I have to "GetComponent<NameScirpt>" probably Im missing something or is really intended to be like this? The idea of my scirpt is that OnTriggerEnter -> Check Many Boolean(Like Blue = false; Red = true; *this values may change after ingame interation) -> Good or Bad(Give a feedback based on the color)
    Code (CSharp):
    1. public class CheckFinish : MonoBehaviour
    2. {
    3.  
    4.     public GameObject Player;
    5.  
    6.     void Awake()
    7.     {
    8.         Player = GameObject.FindWithTag("Player");
    9.     }
    10.  
    11.  
    12.     void OnTriggerEnter(Collider collision)
    13.     {
    14.         if (collision.gameObject.tag == "Player")
    15.         {
    16.             CheckColor();
    17.         }
    18.     }
    19.  
    20.  
    21.     void CheckColor()
    22.     {
    23.         MovementPlayer PlayerScr = Player.GetComponent<MovementPlayer>();
    24.        // Many Check if is the Correct color
    25.        if(PlayerScr.Red == true)
    26.          {
    27.             Good();
    28.           }
    29.     }
    30.  
    31.  
    32.  
    33.     private void Good()
    34.     {
    35.         // I had to call another time GetComponent Because he could't find PlayerScr
    36.         MovementPlayer PlayerScr = Player.GetComponent<MovementPlayer>();
    37.         PlayerScr.enabled = !PlayerScr.enabled;
    38.         Debug.Log("Disabled");
    39.     }
    40. }
    41.  
     
  2. ihgyug

    ihgyug

    Joined:
    Aug 5, 2017
    Posts:
    194
    You get the component at start, only 1 time and then use the variable.
    That would be better.
     
  3. AzoR725

    AzoR725

    Joined:
    Feb 17, 2018
    Posts:
    3
    I Thought the same, i did it but still I get the error "PlayerScr does not exist in this context"
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It's possible that you created a local variable in Start(), then. You want to create the variable outside of any method, and assign it inside Start().
     
    AzoR725 likes this.
  5. AzoR725

    AzoR725

    Joined:
    Feb 17, 2018
    Posts:
    3
    Yea that's what was missing, thanks!!
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You're welcome :)