Trying to instantiate and set up a SphereCollider in C# Script. Getting Errors.

I’ve tried many ways after looking through the forums and well I cant seem to figure it out. I’m new to unity but and a lil rusty on C#, mainly a C++ coder.

So here’s what I’ve tried.

I am making a simple script to make a light blink, and then ill be doing some Raycasting to see if a player looks at the light and then turn it off when they do. I figured a quick SphereCollider is all i needed.

If i have posted this in the wrong format or something I apologize, as this is my first post to the forums community. Thanks for any help you can give me.

The errors are with me trying to set the center and radius.
NullReference Exceptions.

//////////////////////////////////////CODE Snippet////////////////////////////////////////////////

using UnityEngine;
using System.Collections;

public class Blinker : MonoBehaviour {
	
	public float m_fBlinkSpeed = 2.0f;
	public float m_fRange = 100.0f;
	
	private bool m_bShouldIBlink = true;
	private SphereCollider m_Collider;
	public Light m_Blinker;
	bool m_bDimming = true;
	bool m_bBrightening = false;
	
	// Use this for initialization
	void Start()
	{

          //Attempt 1: my C++ way
          m_Collider = new SphereCollider();
          m_Collider.center = m_bBlinker.transform.position;
          m_Collider.radius = 5.0f;

          //Attempt 2: Forums Unity stuff
          //m_Collider = m_Blinker.GetComponent<SphereCollider>();
          //m_Collider.center = m_Blinker.transform.GetComponent<SphereCollider>();
         
	
	}

/////////////////////////////////////// Code Snippet/////////////////////////////////

The SphereCollider is an Unity component - I suspect it can’t fully exist without being attached to a GameObject. If m_Blinker refers to a scene object, you can try this:

  // AddComponent creates the object and links it to the game object:
  m_Collider = m_Blinker.gameObject.AddComponent<SphereCollider>();
  m_Collider.center = Vector3.zero; // the center must be in local coordinates
  m_Collider.radius = 5.0f;

Unity components have several “inherited variables” (properties, actually) that depends on its owner GameObject, thus simply instantiating a new component doesn’t make it fully functional.

You can put a sphereCollider on the object and disable it… And whenever you need your collider just enable or disable your SphereCollider Component…

SphereCollider sphere;

void Start(){

sphere = gameObject.GetComponent<SphereCollider>();

sphere.enabled = false;

}

void Update(){
//if you want to enable it

if(your conditions...){

sphere.enabled = true;

}


}

but remember Sphere collider will not work if RigidBody is not attached to the Game object