GetComponent returning null with no errors
I am trying to set the difficulty based on the players chosenDifficulty, but when I use GetComponent on an instantiated object, it does not find the chosenDifficulty.
I have tried putting it into the awake & breaking it into both the awake and the start, but it just doesnt want to return a value.
There are no errors in the console & everything is referenced in the inspector.
I have no idea why this isnt working, any help is greatly appreciated.
Tnx.
1st script:
using UnityEngine;
public class Something : MonoBehaviour
{
public int difficulty;
int chosenDifficulty;
public Thing thing;
public GameObject master; // holder of Thing script
private void Awake()
{
thing = master.GetComponent<Thing>();
chosenDifficulty = thing.chosenDifficulty;
}
void Start()
{
difficulty = chosenDifficulty;
}
}
2nd script:
using UnityEngine;
public class Thing : MonoBehaviour
{
public int chosenDifficulty;
public GameObject empty; // holder of the something script
// Start is called before the first frame update
void Start()
{
chosenDifficulty = 32;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown ("k"))
{
Instantiate(empty, Camera.main.transform);
}
}
}
Answer by xxmariofer · Dec 03, 2020 at 12:53 PM
if
thing.chosenDifficult
doesnt return an error it means that GetComponent is indeed finding the component
The problem ended up being with my GameObject & when I turned it into a Prefab.
I had to rebuild everything & made the same mistake to realise I had linked the object in the scene & not the original prefab.