I'm currently simulating light reflection using raycast in Unity. I want to call the result of collision on an object through raycast in script "A" from script "B", but it doesn't work. I would like to ask if there is a simpler method other than the method using layers. below is my "A" script coding:
if(hitInfo.collider.gameObject.tag == "Mirror")
I want make "B" coding recognize the results of "A" script collision. Thank you in advance.
CodePudding user response:
I don't know if I understand your situation correctly, but if you are doing a Raycast from script "A" and you want to potentially call a function on a hit GameObject with script "B" attached, then you could do something like:
if (hitInfo.collider.gameObject.tag == "Mirror")
{
var b = hitInfo.collider.GetComponent<B>();//Replace B with your script class
if (b != null)
{
b.SomeFunction(float someVariable);//Replace SomeFunction with your function
}
}
However, the GetComponent call is a bit expensive, so if it is something that is done a lot (every frame / many times per frame) it might slow things down. Then, a faster approach could be to let all instances of "B" (if there are more than one) register themselves with their respective colliders somewhere central on Start() or by letting your "A" script look for all instances of "B" when it starts up. The register could then be a Dictionary<Collider,B> where you can quickly find a potential "B" script of a hit collider.