NullRef on my parent script

Ill try explaining this the best i can since english isnt my first language.

So im very new to C# and Unity… im trying to do a RTS, and for this question there are 3 important scripts… Buildings, CivBuilding(has specific civilization stuff for the buildings) and then a specific script for the main building.

i want to have the building firstly without collisions and following my mouse and after i place it, only then i will enable the collision, since i want this behavior on all the buildings i did it on the “buildings” script and i tough since CivBuilding inherits its behavior and the main building script inherits CivBuilding behavior then it would work.

but i get NullReferenceException : Object reference not set to an instance
on these lines

SphereCollider sphere;

public virtual void Start () {
	Built=false;
            sphere = gameObject.GetComponent<SphereCollider>();
	here-> sphere.enabled=false;
}

i think its because both the gerenal building script and the civBuilding script arnt attached to any object…but since my building’s class is abstract i cant add it to any object…

btw, the script works as intended because once it gets to my main building script it recognizes the collider…but i didnt really wanted to have errors on my game…should i use throw exceptions??

sry for the long text and thanks for any answers

The only ways the code you posted can result in a NullReferenceException in line 6 are the following:

  • that’s not the whole Start() method and you removed some lines for readability
  • the object that has this script (or a derived class) attached does not have a SphereCollider attached
  • this script is accidentally attached to an additional object which has no SphereCollider
  • the SphereCollider gets destroyed by a script at some point

One of these must be true. Since your script is working as intended, maybe it’s #3. Maybe a prefab prototype or something similar. Use “Find References in Scene” in the context menu in the “Project” tab on all building classes to find their scene instances (assuming you don’t attach/create building objects at runtime).