What I’m trying to do is for a ‘buy button’ to show when I click on an object i want to buy.
The script does detect the buy button because I made it so that at start it sets it to be not active - and it does work.
.
.
The problem I am having is that I get an error saying “The variable ‘buyButton’ of ‘Colors’ has not been assigned” when I try to set the button to be active with a public function using another button. It points me to a public GameObject variable that I have actually assigned in the inspector.
I also tried assigning it with GameObject.FindWithTag but that made no difference
.
.
I’m assuming it’s because it’s accessing it from a public function and it somehow looses the reference to that object? I just don’t know how and what to do to make it not do that. Any help would be appreciated.
If the errors says “has not been assigned” you can be sure, that indeed some reference has not been assigned in the inspector. The most likely cause of your issue is, that you’ve assigned some variable, but there’s another object with the same script attached, where you didn’t assign it. To find the culprit you can log a debug line to the console and send the current instance as a context with the log statement. This way, when you click (or double-click) the log statement in the console, Unity will highlight the respective GameObject.
public Transform someVariable;
void Start()
{
if(someVariable == null)
Debug.LogError("SomeVariable has not been assigned.", this) ;
// Notice, that we pass 'this' as a context object so that Unity will highlight this object when clicked.
}
Additionally, make sure that you are actually modifying only the object you intend to, not a prefab or some duplicate in the scene. To make sure, I would create a new scene and place (or recreate) only the relevant objects for testing.
Assigning with GameObject.FindWithTag is not required and I wouldn’t recommend it here. Just find the missing reference on one of your objects and set it manually.
I don’t think the problem has a connection to any public function and Unity doesn’t lose references in a way that matches what you describe. The only way for Unity to lose a reference would be if the referenced object would be destroyed or the field was set to null by another script. However, if any of this happened, Unity would log an error saying “missing reference exception, the object has been destroyed” or simply “null reference exception, the object is null”. Since the error was “has not been assigned” we can be sure, that Unity has already noticed that nobody set the variable at runtime, instead it was null from the beginning.
Good luck! If nothing helps, create a small UnityPackage showing your problem and somebody here can take a look. 