- Home /
How do I determine the presence of a script on an object?
I am new to Unity, and I'm working in C#.
I created a plane. On this plane are two objects. Object #1 which has a script called myReverbNode, and object #2 which has a script called myAudioController. myAudioController Checks its object's vicinity for objects with the myReverbNode script.
I am using Physics.OverlapSphere to locate objects within a radius. Once this is done, I want to use the array it returns to test the objects that were found for the presence of the myReverbNode script.
However, although an object with the myReverbNode script is within the radius, myAudioController keeps telling me that var myScript is null.
I'm possibly being retarded on multiple levels, as I'm new to Unity. But, please take a look at my script, and see if there are any obvious problems/things I didn't take into account. All help/tips/advice is welcome, and if I've left out vital information, let me know.
myAudioController.cs
float myRadius = 250;
void Update ()
{
Collider[] objectsHit = Physics.OverlapSphere(transform.position, myRadius);
int a = 0;
while (a < objectsHit.Length)
{
var myScript = objectsHit[a].GetComponent<myReverbNode>();
if (myScript != null)
{
//Do stuff.
}
if (myScript == null)
{
Debug.Log("myScript is null.");
}
a++;
}
}
Answer by Benproductions1 · Apr 10, 2013 at 04:29 AM
If you want to check wether there is a component on an object, you can simply do:
if (OtherObject.GetComponent(MyComponent)) {
//This only happens when we have MyComponent attached to OtherObject
}
Hope this helps, Benproductions1
Your answer
![](https://koobas.hobune.stream/wayback/20220613100021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why is this null? Finding a script on an object 3 Answers
get component null reference 2 Answers
GetComponent hates me 2 Answers
Assign collider and linerenderer to list 1 Answer
Unity GetComponent return value 2 Answers