- Home /
GetComponent sometimes doesn't work
First of all, hi, this is my first question on the forums and I'm also new to Unity (and programming).
Now, my problem is this: I need to access a variable from another script but for some weird reason it won't work.
This is the script that needs to access the variable:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class updateWood : MonoBehaviour
{
public Items itemsScript;
public UnityEngine.UI.Text textC;
private RectTransform rt;
private int wood = 0;
private int nWood = 0;
// Start is called before the first frame update
void Start()
{
itemsScript = rt.parent.parent.parent.GetComponent<Items>().itemsScript;
rt = this.GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
nWood = itemsScript.wood;
}
And this is the script that contains the variable:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Items : MonoBehaviour
{
public Items itemsScript;
void Awake()
{
itemsScript = GetComponent<Items>();
}
}
I know that should work because other scripts can access the same variable without problem, but oddly if I comment the itemsScript = rt.parent.parent.parent.GetComponent<Items>().itemsScript;
line and change nWood = itemsScript.wood;
with nWood = rt.parent.parent.parent.GetComponent<Items>().wood;
everything works as intended.
I am clueless and this is killing me right now. Thanks in advanve
Answer by rh_galaxy · Sep 21, 2020 at 10:52 PM
In your Start() in the first script, you need to reverse the order of the two rows you have there... rt need to be assigned before you can use it.
rt = this.GetComponent<RectTransform>();
itemsScript = rt.parent.parent.parent.GetComponent<Items>().itemsScript;
omg you are right, I'm sorry for making such a dumb question. And thanks a lot!
By the way, can I make you another question if it is regarding GetComponent or should I open another thread instead?
Open a new thread if you think it's a new question. just remember to check google or UnityAnswer if there's someone who might already answered your question