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

Yet another 'Object reference not set to an instance of an object'

Discussion in 'Scripting' started by DustyShinigami, May 5, 2019.

  1. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    This seems to be a common error newbies keep getting, and I'd like to learn how to avoid this one properly as I'm always getting caught out by it.

    I'm not sure what I'm missing to get this error, but I have a method in one script being referenced in another and calls it when needed. I have the script to be referenced (in this case, HutTrigger) as a variable at the top, I have GetComponent in the Start function, and then the method is called under the ControllerDetection function if the Xbox 360 controller is detected. The required game objects have been placed in the boxes the script is attached to, so I'm not sure what I'm missing to cause this error.

    PlayerController script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class PlayerController : MonoBehaviour
    7. {
    8.     public Animator anim;
    9.     public float moveSpeed;
    10.     public float jumpForce;
    11.     public bool jumped;
    12.     public bool attack;
    13.     public float gravityScale;
    14.     public float knockBackForce;
    15.     public float knockBackTime;
    16.     public float invincibilityLength;
    17.     public Renderer playerRenderer;
    18.     public Material textureChange;
    19.     public Material textureDefault;
    20.     public bool allowCombat = false;
    21.     public bool multipleDirections = false;
    22.     public float rotateSpeed;
    23.     public HutTrigger hutTrigger;
    24.  
    25.     private float jumpDelay;
    26.     private Vector3 moveDirection;
    27.     private Vector3 extraDirections;
    28.     private float knockBackCounter;
    29.     private float invincibilityCounter;
    30.     private CharacterController controller;
    31.     private int xbox360Controller = 0;
    32.     private int ps4Controller = 0;
    33.  
    34.     void Start()
    35.     {
    36.         Cursor.visible = false;
    37.         controller = GetComponent<CharacterController>();
    38.         hutTrigger = GetComponent<HutTrigger>();
    39.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("level 1"))
    40.         {
    41.             allowCombat = true;
    42.             multipleDirections = false;
    43.         }
    44.         else if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("start_area"))
    45.         {
    46.             allowCombat = false;
    47.             multipleDirections = false;
    48.         }
    49.         else if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("hut_interior"))
    50.         {
    51.             allowCombat = false;
    52.             multipleDirections = true;
    53.         }
    54.     }
    55.  
    56.     void Update()
    57.     {
    58.         if (knockBackCounter <= 0)
    59.         {
    60.             float moveHorizontal = Input.GetAxis("Horizontal");
    61.             moveDirection = new Vector3(moveHorizontal * moveSpeed, moveDirection.y);
    62.  
    63.             if (moveHorizontal > 0)
    64.             {
    65.                 transform.eulerAngles = new Vector3(0, 90);
    66.             }
    67.             else if (moveHorizontal < 0)
    68.             {
    69.                 transform.eulerAngles = new Vector3(0, -90);
    70.             }
    71.             if (controller.isGrounded)
    72.             {
    73.                 moveDirection.y = -1f;
    74.                 //GetKeyDown will require the player to press the button each time they want to jump. GetKey will allow the player to spam the jump button if they keep pressing it down.
    75.                 if (Input.GetKeyDown(KeyCode.KeypadPlus) || Input.GetKeyDown("joystick button 1"))
    76.                 {
    77.                     moveDirection.y = jumpForce;
    78.                     jumped = true;
    79.                 }
    80.                 else if (!Input.GetKeyDown(KeyCode.KeypadPlus) || !Input.GetKeyDown("joystick button 1"))
    81.                 {
    82.                     jumped = false;
    83.                 }
    84.                 if (allowCombat)
    85.                 {
    86.                     if (Input.GetKey(KeyCode.Space) || Input.GetKey("joystick button 7"))
    87.                     {
    88.                         attack = true;
    89.                         playerRenderer.material = textureChange;
    90.                     }
    91.                     else if (!Input.GetKey(KeyCode.Space) || !Input.GetKey("joystick button 7"))
    92.                     {
    93.                         attack = false;
    94.                         playerRenderer.material = textureDefault;
    95.                     }
    96.                 }
    97.                 else if (!allowCombat)
    98.                 {
    99.                     attack = false;
    100.                     playerRenderer.material = textureDefault;
    101.                 }
    102.  
    103.             }
    104.         }
    105.         else
    106.         {
    107.             knockBackCounter -= Time.deltaTime;
    108.         }
    109.  
    110.         moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
    111.         controller.Move(moveDirection * Time.deltaTime);
    112.  
    113.         anim.SetBool("isGrounded", controller.isGrounded);
    114.         anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
    115.         if (attack)
    116.         {
    117.             anim.SetTrigger("Attack");
    118.         }
    119.  
    120.     }
    121.  
    122.     public void ControllerDetection()
    123.     {
    124.         string[] names = Input.GetJoystickNames();
    125.         for (int x = 0; x < names.Length; x++)
    126.         {
    127.             //print(names[x].Length);
    128.             if (names[x].Length == 19)
    129.             {
    130.                 //print("PS4 CONTROLLER IS CONNECTED");
    131.                 ps4Controller = 1;
    132.                 xbox360Controller = 0;
    133.             }
    134.             if (names[x].Length == 33)
    135.             {
    136.                 //print("XBOX 360 CONTROLLER IS CONNECTED");
    137.                 ps4Controller = 0;
    138.                 xbox360Controller = 1;
    139.             }
    140.             if (xbox360Controller == 1)
    141.             {
    142.                 hutTrigger.Xbox360Prompts();
    143.             }
    144.             else if (ps4Controller == 1)
    145.             {
    146.  
    147.             }
    148.             else
    149.             {
    150.  
    151.             }
    152.         }
    153.     }
    154.  
    155.     public void Knockback(Vector3 direction)
    156.     {
    157.         knockBackCounter = knockBackTime;
    158.  
    159.         moveDirection = direction * knockBackForce;
    160.         moveDirection.y = knockBackForce;
    161.     }
    162.  
    163.     /*public Vector3 GetTravelDirection()
    164.     {
    165.         return moveDirection.normalized;
    166.     }*/
    167. }
    HutTrigger script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6.  
    7. public class HutTrigger : MonoBehaviour
    8. {
    9.     public static bool hutLoaded;
    10.     public GameObject[] buttonPrompts;
    11.     public bool entranceVicinity;
    12.  
    13.     private PlayerController playerController;
    14.  
    15.     void Start()
    16.     {
    17.         playerController = FindObjectOfType<PlayerController>();
    18.     }
    19.  
    20.     public void OnTriggerEnter(Collider other)
    21.     {
    22.         if (other.gameObject.CompareTag("Player"))
    23.         {
    24.             entranceVicinity = true;
    25.             playerController.ControllerDetection();
    26.             //buttonPrompt1.SetActive (true);
    27.             //Invoke("Hide", 3f);
    28.         }
    29.     }
    30.  
    31.     void Update()
    32.     {
    33.         if (entranceVicinity)
    34.         {
    35.             if (Input.GetKeyDown("joystick button 2"))
    36.             {
    37.                 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2);
    38.                 hutLoaded = true;
    39.             }
    40.         }
    41.     }
    42.  
    43.     public void Hide()
    44.     {
    45.         buttonPrompts[0].SetActive (false);
    46.         buttonPrompts[2].SetActive(false);
    47.     }
    48.  
    49.     public void Xbox360Prompts()
    50.     {
    51.         buttonPrompts[0].SetActive(true);
    52.         Invoke("Hide", 3f);
    53.     }
    54.  
    55.     public void PCPrompts()
    56.     {
    57.         buttonPrompts[2].SetActive(true);
    58.         Invoke("Hide", 3f);
    59.     }
    60. }
    Can someone help me clear up the confusion? Thanks.
     
  2. vs
    Code (CSharp):
    1. hutTrigger = GetComponent<HutTrigger>();
    I'm not sure I understand what are you doing, because your text wasn't clear on this, but if you run GetComponent<>() and the component is not on the current game object (as I assume), then it will overwrite the hutTrigger with null.

    If this is not the case, please post the exact error with line number (if it's not the same in the code above, please, tell us which line the error in)
     
  3. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I'm not sure what you mean. I thought that's what GetComponent does - it gets the HutTrigger script and sort of attaches it to that PlayerController script...? Or rather, it allows access to the contents of that script...?
     
  4. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Ohhhh, I think I get it. Correct me if I'm wrong though. So whenever I add a GetComponent and call for a script, I also need to add a public variable GameObject, which will be the object the script is originally attached to?
     
  5. Just remove the line from code, keep the public HutTrigger hutTrigger; line and just drag and drop the proper game object in the inspector, your code will have access to the component without the GetComponent.
     
    TaleOf4Gamers and DustyShinigami like this.
  6. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Despite referencing a GameObject with the required script AND having GetComponent at the start, I'm still having the same error come up for another issue. :(

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class ExitTrigger : MonoBehaviour
    7. {
    8.     public GameObject[] buttonPrompts;
    9.     public bool exitVicinity;
    10.     public GameObject thePlayer;
    11.     public GameObject entranceObject;
    12.  
    13.     private int xbox360Controller = 0;
    14.     private int ps4Controller = 0;
    15.     private bool insideHut;
    16.     private EntranceTrigger entranceTrigger;
    17.     //private EntranceTrigger entranceTrigger;
    18.  
    19.     void Start()
    20.     {
    21.         entranceTrigger = GetComponent<EntranceTrigger>();
    22.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("hut_interior"))
    23.         {
    24.             insideHut = true;
    25.             exitVicinity = true;
    26.         }
    27.     }
    28.  
    29.     public void OnTriggerEnter(Collider other)
    30.     {
    31.         if (insideHut)
    32.         {
    33.             if (other.gameObject.CompareTag("Player"))
    34.             {
    35.                 exitVicinity = true;
    36.                 ControllerDetection();
    37.                 if (exitVicinity && ps4Controller == 1)
    38.                 {
    39.                     PS4Prompts();
    40.                 }
    41.                 else if (exitVicinity && xbox360Controller == 1)
    42.                 {
    43.                     Xbox360Prompts();
    44.                 }
    45.                 else
    46.                 {
    47.                     PCPrompts();
    48.                 }
    49.             }
    50.         }
    51.     }
    52.  
    53.     public void OnTriggerExit(Collider other)
    54.     {
    55.         exitVicinity = false;
    56.     }
    57.  
    58.     public void Update()
    59.     {
    60.         if (exitVicinity)
    61.         {
    62.             if (xbox360Controller == 1)
    63.             {
    64.                 if (Input.GetKeyDown("joystick button 2"))
    65.                 {
    66.                     SceneManager.LoadScene("start_area");
    67.                 }
    68.             }
    69.             else if (ps4Controller == 1)
    70.             {
    71.                 if (Input.GetKeyDown("joystick button 0"))
    72.                 {
    73.                     SceneManager.LoadScene("start_area");
    74.                 }
    75.             }
    76.             else
    77.             {
    78.                 if (Input.GetKeyDown(KeyCode.Return))
    79.                 {
    80.                     SceneManager.LoadScene("start_area");
    81.                     entranceTrigger.PlayerReload();
    82.                 }
    83.             }
    84.         }
    85.     }
    86.  
    87.     public void Hide()
    88.     {
    89.         buttonPrompts[0].SetActive(false);
    90.         buttonPrompts[1].SetActive(false);
    91.         buttonPrompts[2].SetActive(false);
    92.     }
    93.  
    94.     public void Xbox360Prompts()
    95.     {
    96.         buttonPrompts[1].SetActive(true);
    97.         Invoke("Hide", 3f);
    98.     }
    99.  
    100.     public void PS4Prompts()
    101.     {
    102.         buttonPrompts[2].SetActive(true);
    103.         Invoke("Hide", 3f);
    104.     }
    105.  
    106.     public void PCPrompts()
    107.     {
    108.         buttonPrompts[0].SetActive(true);
    109.         Invoke("Hide", 3f);
    110.     }
    111.  
    112.     public void ControllerDetection()
    113.     {
    114.         string[] names = Input.GetJoystickNames();
    115.         for (int x = 0; x < names.Length; x++)
    116.         {
    117.             //print(names[x].Length);
    118.             if (names[x].Length == 19)
    119.             {
    120.                 //print("PS4 CONTROLLER IS CONNECTED");
    121.                 ps4Controller = 1;
    122.                 xbox360Controller = 0;
    123.                 if (ps4Controller == 1)
    124.                 {
    125.                     Debug.Log("PS4 controller detected");
    126.                 }
    127.             }
    128.             else if (names[x].Length == 33)
    129.             {
    130.                 //print("XBOX 360 CONTROLLER IS CONNECTED");
    131.                 ps4Controller = 0;
    132.                 xbox360Controller = 1;
    133.                 if (xbox360Controller == 1)
    134.                 {
    135.                     Debug.Log("Xbox 360 controller detected");
    136.                 }
    137.             }
    138.             else
    139.             {
    140.                 ps4Controller = 0;
    141.                 xbox360Controller = 0;
    142.             }
    143.  
    144.             if (xbox360Controller == 0 && ps4Controller == 0)
    145.             {
    146.                 Debug.Log("No controllers detected");
    147.             }
    148.  
    149.             /*if (!string.IsNullOrEmpty(names[x]))
    150.             {
    151.                 xbox360Controller = 1;
    152.                 ps4Controller = 1;
    153.             }
    154.  
    155.             else if(string.IsNullOrEmpty(names[x]))
    156.             {
    157.                 xbox360Controller = 0;
    158.                 ps4Controller = 0;
    159.                 Debug.Log("Controllers not detected");
    160.             }*/
    161.         }
    162.     }
    163. }
    164.  
    I get the issue on line 81 and I have no idea why.
     
  7. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    Well, obviously entranceTrigger is null. Are you sure that
    Code (csharp):
    1. entranceTrigger = GetComponent<EntranceTrigger>();
    Actually found anything?
     
  8. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I don’t understand why it hasn’t though. I made a reference to the game object, the script it’s attached to, I’ve placed the object in the Inspector box. Not sure what else I could be missing.
     
  9. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    that's waht @Lurking-Ninja was trying to explain before. You can put a reference in the inspector box all you want, but as soon as that GetComponent fails, that assignment statement is going to throw-away whatever was in your inspector box and replace it with null.

    If you are going to set the reference in the inspector, but then get rid of the GetComponent.

    Either that, or you can change the GetComponent code to this:
    Code (csharp):
    1.  
    2. if (entranceTrigger == null)
    3. {
    4.      entranceTrigger = GetComponent<EntranceTrigger>();
    5. }
    6.  
    That way, if you already assigned the reference in the inspector, than the assignment statement will leave it alone and not change it.
     
  10. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    But why would GetComponent fail? I don't get it at all. :( Pretty much every time I've used a GetComponent on Start it works, so what's different in this case?
     
  11. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    You definitely have a EntranceTrigger component on the same object as your ExitTrigger script?
     
  12. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Nnnno, I don't. I thought that's what GetComponent did though...? That it gets a component, such as a gameobject with a script so it can access it. Hence the reason for making a reference to a game object and dragging it into the Inspector so it knows what object to access it from?
     
  13. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    A GameObject is not a Component. A Component is something that you attach to a GameObject, like a monobehaviour script, Renderer, RigidBody, etc. When you call GetComponent, it only looks for Components that are attached to the same GameObject that you call it from. If you want a Component that's on a different GameObject then you have to get a reference to that GameObject and then call GetComponent from that reference.

    Or you can just assign it in the inspector, like you're doing now, but in that case just get rid of that GetComponent code.
     
    DustyShinigami likes this.
  14. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Right, it's starting to make sense. Thanks. I'll try experimenting a bit more. :)
     
  15. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I take it FindObjectofType will find any component *and* gameobject on other gameobjects then?
     
  16. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I'm probably just being dumb, but as an experiment, I have my SceneManagement script attached to my ExitTrigger, and that script contains a GameManager component called theGameManager, and then a GetComponent is called on Start. I've dropped the GameObject the GameManager script is attached to in the Inspector, but once Play is pressed, it disappears from the box.
     
  17. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    What do you mean by that script contains a component?
     
  18. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I’m not even sure anymore. I’m guessing I actually meant a GameManager variable...
     
  19. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    But then I've just tried the same thing with something else where I'm trying to get the PlayerController from the Player object. The PlayerController is a script, though isn't a script a component...?
     
  20. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    It should be, if it inherits from MonoBehaviour.

    Edit: To clarify it further, when you create a new script in Unity, it creates a class definition with the same name. So in PlayerController, you should see line that looks like:

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    That ": MonoBehaviour" means that PlayerController inherits a class called
    MonoBehaviour which is defined in Unity. This class, in turn, inherits from a class called Component which is the class that defines a Unity Component and it's what Unity uses to interface with Components. So any class that you define that inherits from MonoBehaviour is also a component.
     
    Last edited: May 11, 2019
  21. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Which all of my scripts do, so this is just adding more to my confusion. In my SceneManagement script, I've made a variable 'private PlayerController thePlayerController'. This is the PlayerController script attached to my Player game object. And I've put a reference 'public GameObject player'. Then finally I've dropped the Player game object into the Inspector. Based on what you've told me previously, this component is on a different game object, hence the 'player' game object reference. So I don't understand why this isn't working. :-\

    EDIT: To clarify, it looks to be complaining about another line of code, which I may have done wrong. It's complaining about my line player.transform.position = spawnPoint[0].position;
     
    Last edited: May 11, 2019
  22. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    Can you post the code that isn't working?
     
  23. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I'm trying to get my player to go back to a certain position in my first scene. But to get there, I need the player to go from another scene. I tried setting up a Transform, which I'm trying to use the trigger that causes the player to go to the second scene. I'm not sure if my SceneManager.LoadScene is preventing it from working by resetting everything, or what. It's line 147 that won't work and gives me the usual 'Object reference not set to an instance of an object'. I'm at the end of my rope trying to fix this issue, but everything I've done won't work. I'm about ready to give up.

    This is the script I have:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6.  
    7. public class SceneManagement : MonoBehaviour
    8. {
    9.     public GameObject[] buttonPrompts;
    10.     public Transform spawnPoint;
    11.     public GameObject player;
    12.     //public GameManager gameManager;
    13.     //public HealthManager theHealthManager;
    14.     public bool entranceVicinity;
    15.     //public float reloadLength;
    16.     public bool exitVicinity;
    17.     public string levelToLoad;
    18.     //public bool allowInteraction = false;
    19.  
    20.     //public PlayerController thePlayerController;
    21.  
    22.     private int xbox360Controller = 0;
    23.     private int ps4Controller = 0;
    24.     private bool outsideHut;
    25.     private bool insideHut;
    26.     //private Vector3 respawnPoint;
    27.     //private bool playerReloading;
    28.  
    29.     void Start()
    30.     {
    31.         //gameManager = FindObjectOfType<GameManager>();
    32.         //theHealthManager = FindObjectOfType<HealthManager>();
    33.         //player = GameObject.Find("Player");
    34.         //thePlayerController = GetComponent<PlayerController>();
    35.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("start_area"))
    36.         {
    37.             outsideHut = true;
    38.         }
    39.         if(SceneManager.GetActiveScene() == SceneManager.GetSceneByName("hut_interior"))
    40.         {
    41.             insideHut = true;
    42.             outsideHut = false;
    43.         }
    44.     }
    45.  
    46.     public void OnTriggerEnter(Collider other)
    47.     {
    48.         if (outsideHut)
    49.         {
    50.             //respawnPoint = thePlayer.transform.position;
    51.             if (other.gameObject.CompareTag("Player"))
    52.             {
    53.                 entranceVicinity = true;
    54.                 exitVicinity = false;
    55.                 ControllerDetection();
    56.                 if (entranceVicinity && ps4Controller == 1)
    57.                 {
    58.                     PS4Prompts();
    59.                 }
    60.                 else if (entranceVicinity && xbox360Controller == 1)
    61.                 {
    62.                     Xbox360Prompts();
    63.                 }
    64.                 else
    65.                 {
    66.                     PCPrompts();
    67.                 }
    68.             }
    69.         }
    70.         else if (insideHut)
    71.         {
    72.             if (other.gameObject.CompareTag("Player"))
    73.             {
    74.                 //SetSpawnPoint(transform.position);
    75.                 entranceVicinity = false;
    76.                 exitVicinity = true;
    77.                 ControllerDetection();
    78.                 if (entranceVicinity && ps4Controller == 1)
    79.                 {
    80.                     PS4Prompts();
    81.                 }
    82.                 else if (entranceVicinity && xbox360Controller == 1)
    83.                 {
    84.                     Xbox360Prompts();
    85.                 }
    86.                 else
    87.                 {
    88.                     PCPrompts();
    89.                 }
    90.             }
    91.         }
    92.     }
    93.  
    94.     public void OnTriggerExit(Collider other)
    95.     {
    96.         entranceVicinity = false;
    97.         exitVicinity = false;
    98.     }
    99.  
    100.     public void Update()
    101.     {
    102.         if (entranceVicinity)
    103.         {
    104.             if (xbox360Controller == 1)
    105.             {
    106.                 if (Input.GetKeyDown("joystick button 2"))
    107.                 {
    108.                     SceneManager.LoadScene(levelToLoad);
    109.                 }
    110.             }
    111.             else if (ps4Controller == 1)
    112.             {
    113.                 if (Input.GetKeyDown("joystick button 0"))
    114.                 {
    115.                     SceneManager.LoadScene(levelToLoad);
    116.                 }
    117.             }
    118.             else
    119.             {
    120.                 if (Input.GetKeyDown(KeyCode.Return))
    121.                 {
    122.                     SceneManager.LoadScene(levelToLoad);
    123.                 }
    124.             }
    125.         }
    126.         else if (exitVicinity)
    127.         {
    128.             if (xbox360Controller == 1)
    129.             {
    130.                 if (Input.GetKeyDown("joystick button 2"))
    131.                 {
    132.                     SceneManager.LoadScene(levelToLoad);
    133.                 }
    134.             }
    135.             else if (ps4Controller == 1)
    136.             {
    137.                 if (Input.GetKeyDown("joystick button 0"))
    138.                 {
    139.                     SceneManager.LoadScene(levelToLoad);
    140.                 }
    141.             }
    142.             else
    143.             {
    144.                 if (Input.GetKeyDown(KeyCode.Return))
    145.                 {
    146.                     //SceneManager.LoadScene(levelToLoad);
    147.                     player.transform.position = spawnPoint.position;
    148.                     //PlayerReload();
    149.                 }
    150.             }
    151.         }
    152.     }
    153.  
    154.     /*public void PlayerReload()
    155.     {
    156.         if (!playerReloading)
    157.         {
    158.             StartCoroutine("ReloadingCo");
    159.         }
    160.     }
    161.  
    162.     public IEnumerator ReloadingCo()
    163.     {
    164.         Instantiate(player, player.transform.position, player.transform.rotation);
    165.         yield return new WaitForSeconds(reloadLength);
    166.         playerReloading = false;
    167.         player.transform.position = respawnPoint;
    168.     }
    169.  
    170.     public void SetSpawnPoint(Vector3 newPosition)
    171.     {
    172.         respawnPoint = newPosition;
    173.     }*/
    174.  
    175.     public void Hide()
    176.     {
    177.         buttonPrompts[0].SetActive(false);
    178.         buttonPrompts[1].SetActive(false);
    179.         buttonPrompts[2].SetActive(false);
    180.     }
    181.  
    182.     public void Xbox360Prompts()
    183.     {
    184.         buttonPrompts[1].SetActive(true);
    185.         Invoke("Hide", 3f);
    186.     }
    187.  
    188.     public void PS4Prompts()
    189.     {
    190.         buttonPrompts[2].SetActive(true);
    191.         Invoke("Hide", 3f);
    192.     }
    193.  
    194.     public void PCPrompts()
    195.     {
    196.         buttonPrompts[0].SetActive(true);
    197.         Invoke("Hide", 3f);
    198.     }
    199.  
    200.     public void ControllerDetection()
    201.     {
    202.         string[] names = Input.GetJoystickNames();
    203.         for (int x = 0; x < names.Length; x++)
    204.         {
    205.             //print(names[x].Length);
    206.             if (names[x].Length == 19)
    207.             {
    208.                 //print("PS4 CONTROLLER IS CONNECTED");
    209.                 ps4Controller = 1;
    210.                 xbox360Controller = 0;
    211.                 if (ps4Controller == 1)
    212.                 {
    213.                     Debug.Log("PS4 controller detected");
    214.                 }
    215.             }
    216.             else if (names[x].Length == 33)
    217.             {
    218.                 //print("XBOX 360 CONTROLLER IS CONNECTED");
    219.                 ps4Controller = 0;
    220.                 xbox360Controller = 1;
    221.                 if (xbox360Controller == 1)
    222.                 {
    223.                     Debug.Log("Xbox 360 controller detected");
    224.                 }
    225.             }
    226.             else
    227.             {
    228.                 ps4Controller = 0;
    229.                 xbox360Controller = 0;
    230.             }
    231.  
    232.             if(xbox360Controller == 0 && ps4Controller == 0)
    233.             {
    234.                 Debug.Log("No controllers detected");
    235.             }
    236.  
    237.             /*if (!string.IsNullOrEmpty(names[x]))
    238.             {
    239.                 xbox360Controller = 1;
    240.                 ps4Controller = 1;
    241.             }
    242.  
    243.             else if(string.IsNullOrEmpty(names[x]))
    244.             {
    245.                 xbox360Controller = 0;
    246.                 ps4Controller = 0;
    247.                 Debug.Log("Controllers not detected");
    248.             }*/
    249.         }
    250.     }
    251. }
     
  24. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    Is SceneManagement in a different scene than the player object? Assigning a component in the inspector doesn't work across scenes.

    In your OnTriggerEnter, if other.gameObject.CompareTag("Player") is true than other.gameObject will refer to the player, so you can set "player" in there. Otherwise, you could get a reference using FindObjectsWithTag or something like that.
     
  25. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I have SceneManagement attached to an object in both scenes - one on the entrance trigger object, and one on the exit.
     
  26. Okay, couple of things.

    - you should never name your classes to any of the already used classes or namespaces (SceneManagement), sooner or later you will have serious problems because of it, and if tracking down a simple null is problematic, finding bugs which involves overdefined classes will be a true nightmare for you. Just don't do it, find a unique name for your class
    - You're using SceneManager.LoadScene in this file extensively: are you sure you aren't loading a new scene before the error happening (if you're trying to add new content, then you will need to use the LoadSceneMode.Additive mode, see the manual on the link)? Since you chose to load scenes on a destructive way you will load the newe scene and destroy the old one as soon as the engine hits the LoadScene lines (which means the original variables will be null and everything starts over with a new set of variables and objects and scene)
    - tracking down a null-exception starts with the basics:
    you have this line which throws error: player.transform.position = spawnPoint.position;
    - what is null here? Do you know? Because I don't.
    - start to debug 'like a pro', put Debug.Log above the line and write out both the 'player' and the 'spawnPoint' variables and see which one is null.
     
  27. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    This is still confusing the hell out of me. So if I'm trying to access a Component that's already attached to the GameObject (in this case, the player), I only need to put GetComponent? So, for instance, I want the player's CharacterController... Do I just put GetComponent<CharacterController>(); and that's it...? No reference such as public CharacterController theController;...? I thought I need a reference if I'm going to refer to it within the script, such as theController...? Or do you just put CharacterController every time (CharacterController.isGrounded)?

    And as for assigning a component in the Inspector if it's on a different GameObject - that doesn't appear to work for scripts. If I put a reference to my NPC script - public NPC theNPC - and an empty box appears in the Inspector, I can't drag and drop that script in.
     
  28. Ok, I see you have major confusion here, let me try to make it clear a bit. (Also I urge you to visit Unity Learn section and go through the basic tutorial videos, seeing what they are doing may clear up more)

    So, in Unity you have multiple things:

    - assets (live in the project folder, like material, mesh, etc)
    - script assets (special assets, these are the scripts you're writing)

    - game objects (they live in the hierarchy) and they are special instances which can contain components

    - components (live on assets and they are always script assets on game object) -> you drag and drop script asset onto the game object in the inspector

    So, how can you reference things?

    1; In your scripts, you create a public or [SerializeField] attached variable of type.
    Code (CSharp):
    1. public GameObject foo;
    It will show up in the inspector, you can drag and drop any Game Object from the hierarchy and when you hit play, your script will contain a reference to that game object in the hierarchy.

    How you can access its components?
    Code (CSharp):
    1. foo.GetComponent<RigidBody>().someValue = someOtherValue;
    So you use the GetComponent to reach one particular component. Even if it's your _attached_ script. After this you can change any public variable and call any public method.

    2; You can choose to reference a Component
    Code (CSharp):
    1. public RigidBody foo;
    Now, you can drag and drop a Game Object from the hierarchy which HAS a component of RigidBody on it and this component will be referenced automatically in this variable. So our example above will be shortened like this:
    Code (CSharp):
    1. foo.someValue = someOtherValue;
    3; You can use private variable in your script without dragging and dropping:
    Code (CSharp):
    1. private GameObject foo;
    Then you can find your game object:
    Code (CSharp):
    1. foo = GameObject.Find("Bar");
    This will try to find the Game Object in the hierarchy named "Bar" and if it can be found it will reference it otherwhise foo will be equal to null.
    From here, you can find the components like above. foo.GetComponent...

    You can do the same with the component, after you found the game object you can store a reference to any of its components on the same way I showed you above.

    Hope this make it clear a little bit more.

    The take away: non-script assets can be referenced in the inspector by dragging and dropping. Game Objects from the hiearchy can be referenced in the inspector, Components (script assets on Game Objects in the hiearchy or on other assets in the project folder) can be referenced in the inspector, but Script Assets (the scripts you write in the project window) cannot be referenced directly in the inspector. You can only attach them as Components.

    Disclaimer: this information is by no means whole and exhaustive, I only intended it to clear up current confusion above. There is more to it. :)
     
  29. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    Edit: I'm leaving my post here but @Lurking-Ninja probably explains it more clearly in the above post. ^^^

    getComponent is a function that finds a component on the gameObject it belongs to. If you want, you can store the result in a variable, just like you were thinking:
    Code (csharp):
    1.  
    2. CharacterController theController=GetComponent<CharacterController>();
    3.  
    It's even good practice (better performance) to store it in a variable. so that you don't have to call GetComponent over and over again. If you use GetComponent, though, you don't need to make your "theController" variable public (It's better to make it not public in this case) and you don't have to assign it a value in the inspector because GetComponent will assign it a value instead.

    You don't drag a script on it. The variable needs to refer to a specific component that's on a GameObject that's actually in the same scene. You can actually drag the whole object into the box and it will select the component automatically. For example, if you have an NPC script (like you were saying) and you wanted the NPC to have a reference to the player's PlayerController component, then you could make a public member variable like this:
    Code (csharp):
    1.  
    2. public PlayerController myPlayerController;
    3.  
    Now there will be an empty box in the inspector on the NPC component.
    Then, drag the Player object from the "Hierarchy" window into that box. You'll see that the PlayerController will be assigned.
     
    Last edited: May 17, 2019
  30. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Thanks for trying to explain, guys. Some of the info I knew already, but I shall try to process the rest as best I can. :) Also, I didn’t know that if you make a private variable you can access it with GameObjecf.Find(“ ”). Useful to know.
     
  31. No, you're thinking about it wrong.

    You can't find the private variable.

    Variables in script are containers. You store values in them. Like int foo = 5; -> you store five in the variable.
    On the same way you can store references in variables.

    So when you write GameObject go; you're creating the 'go' variable which can store reference to a GameObject.

    Think about the things you can find in your Hierarchy view like game objects. (Emphasis on the >objects<). Every one of them has an address in the memory. You can use them if you know the address. You can store this address in a variable.
    So after above statements the GameObject go = GameObject.Find("Bar"); line means that you're storing the address of the game object "Bar" in the variable "go".
    Later in your SAME script you can refer to this game object through the stored address in your go variable like this:

    go.SetActive(false); for example. This will refer back to the stored game object, so deactivates it in the hierarchy.

    public and private only means that the variable itself can be used only in your current script (private) or you can use it in other scripts as well (public) but only after you gain the address of this current component's