Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question I am having trouble getting a reference to another class

Discussion in 'Scripting' started by GoodAIUser, Jun 15, 2023.

  1. GoodAIUser

    GoodAIUser

    Joined:
    Jul 15, 2020
    Posts:
    11
    I have this class that I want to get it's location in another class.

    This is the one I want to get:

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlayerMovement : MonoBehaviour
    7. {
    8.     private static PlayerMovement _Instance;
    9.  
    10.     public static PlayerMovement Instance { get { return _Instance; } }
    11.  
    12.     private CharacterController controller;
    13.     private Vector3 rotation;
    14.     private Vector3 ForMove;
    15.  
    16.     Quaternion unused;
    17.     public GameObject compas;
    18.  
    19.     public float GlobalX, GlobalZ;
    20.  
    21.     public bool moving = false;
    22.  
    23.     private float rotdir = 0;
    24.  
    25.     private float compang = 0;
    26.  
    27.     public float RotSpeed = 100;
    28.  
    29.     public float ForSpeed = .5f;
    30.  
    31.     private float RotAmount = 0;
    32.  
    33.     private float ForAmount = 0;
    34.  
    35.     public int direction = 0;
    36.  
    37.     private Quaternion CompRot;
    38.  
    39.     private bool goingForward = false;
    40.    
    41.     void Awake()
    42.     {
    43.         Vector3 glpos;      
    44.         glpos = transform.position;
    45.         GlobalX = glpos.x;
    46.         GlobalZ = glpos.z;
    47.        
    48.        
    49.         controller = GetComponent<CharacterController>();      
    50.     }
    51.  
    52.    
    53.     void Update()
    54.     {
    55.        
    56.         foreach (char c in Input.inputString)
    57.         {
    58.            
    59.         }
    60.  
    61.         if (!moving)
    62.         {
    63.             if (Input.GetKeyDown(KeyCode.LeftArrow))
    64.             {
    65.                 rotdir = -1;
    66.                 direction = (direction + 3) % 4;
    67.                 moving = true;
    68.             }
    69.             if (Input.GetKeyDown(KeyCode.RightArrow))
    70.             {
    71.                 rotdir = 1;
    72.                 direction = (direction + 1) % 4;
    73.                
    74.                 moving = true;
    75.             }
    76.             if (Input.GetKeyDown(KeyCode.UpArrow))
    77.             {
    78.                 moving = true;
    79.                 goingForward = true;
    80.             }
    81.         }
    82.         if (moving)
    83.         {
    84.             if (goingForward)
    85.             {
    86.                 if (ForAmount + ForSpeed * Time.deltaTime >= 2)
    87.                 {
    88.                     ForMove = new Vector3(0, 0, 2 - ForAmount);
    89.                     goingForward = false;
    90.                     moving = false;
    91.                     ForAmount = 0;
    92.                 }
    93.                 else
    94.                 {
    95.                     ForAmount += ForSpeed * Time.deltaTime;
    96.                     ForMove = new Vector3(0, 0, ForSpeed * Time.deltaTime);
    97.                 }
    98.                 ForMove = this.transform.TransformDirection(ForMove);
    99.                 controller.Move(ForMove);
    100.             }
    101.             else
    102.             {
    103.                 if (RotAmount + RotSpeed * Time.deltaTime >= 90)
    104.                 {
    105.                     this.rotation = new Vector3(0, rotdir * (90 - RotAmount), 0);
    106.                     compang += rotdir * (90 - RotAmount);
    107.                     moving = false;
    108.                     RotAmount = 0;
    109.                     rotdir = 0;
    110.                 }
    111.                 else
    112.                 {
    113.                     this.rotation = new Vector3(0, rotdir * RotSpeed * Time.deltaTime, 0);
    114.                     compang += rotdir * RotSpeed * Time.deltaTime;
    115.                     RotAmount += RotSpeed * Time.deltaTime;
    116.                 }
    117.                 this.transform.Rotate(this.rotation);
    118.                 CompRot = Quaternion.Euler(270, compang, 0);
    119.                 compas.transform.localRotation = CompRot;
    120.             }
    121.             Vector3 glpos;
    122.             glpos = transform.position;
    123.             GlobalX = glpos.x;
    124.             GlobalZ = glpos.z;
    125.         }
    126.     }
    127. }
    128.  
    This is one that I want to get the reference:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System;
    5. public class SelfDestroy : MonoBehaviour
    6. {  
    7.     public PlayerMovement ThePlayer;
    8.  
    9.    
    10.     void Update()
    11.     {
    12.         Vector3 selpos = transform.position;
    13.         if (ThePlayer == null)
    14.         {
    15.             return;
    16.         }
    17.        
    18.         if (Math.Abs(selpos.z - ThePlayer.GlobalZ) > 10)
    19.         {
    20.             Destroy(this.gameObject);          
    21.         }
    22.     }
    23. }
    24.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    It isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.


    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that
     
  3. GoodAIUser

    GoodAIUser

    Joined:
    Jul 15, 2020
    Posts:
    11
    I just found I had to place this in my SelfDestroy.

    Code (CSharp):
    1. ThePlayer = GameObject.Find("Player").GetComponent<PlayerMovement>();
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    If it works for you, great, but just so you know what you're getting into here:

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.


    Keep in mind that using GetComponent<T>() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

    This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

    If you run into an issue with any of these calls, start with the documentation to understand why.

    There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

    In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

    It is ALWAYS better to go The Unity Way(tm) and make dedicated public fields and drag in the references you want.