- Home /
Call function only on the Object the player is interacting with. (when there are multiple copys of the object)
Hi, I need help with a little problem.
I have several chairs in a room the player can interact with. On all of them is a copy of a sitting.cs script. The player can enter "Sitting mode" and when standing up leave "sitting mode". In my character controller I call a function when the player presses the key to stand up. However the function is not called on the gameObject the player is sitting on, but allways on the 5th in the hierarchie. I need to call the function only on the gameObject the player is sitting on.
In PlayerController I have:
public void stopSitting()
{
isSitting = false;
sitting.isInSitMode = false;
sitting.resetC();
}
In Sitting.cs there is:
public void resetC()
{
SitCollider.SetActive(true);
}
As said, I have a hand full of objects the Sitting.cs is attached to. How would I call the resetC function and set the bool ONLY on the one I'm interacting with. I understand that I need to check what chair I'm sitting on and than call the function only on the script copy that is on the gameObject. How would I do that? List? Would be nice to see a code example.
Answer by KOCGI · Jan 30 at 08:00 PM
Is it really that incredibly hard that no one in the world can tell me how to fire a function in the nearest Object I find?
Hi man, you could do this on many ways... lots of them depending from your scene setup, and components atached to your Player and Chairs (boxes... so objects to sit...) one of them could be using Coliders atached to Player and Objects...
(1) make a TAG "chair" (2) then in your player script add:
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Chair")
{
other.GetComponent<someScriptOnYourThingToSitOn>();
}
}
(3) so above you will grab things which are near you and you trigger them...
Another way could be checking whole scene for GameObject with TAG... then storing they transform, and when needed checking position to all and calculating nearest...
Also man try to be nice to people, everyone here will try to help you, but not if you not nice to rest. Hope you will manage to solve your issue. I remember one awesome tutorial of how to use colliders (by CodeMonkey) maybe you should spend 10 $$anonymous$$utes on it...
Thanks. In a very strange combination of level setup and events nothing was working out. But it's fixed. I removed the events that where causing the troubles.