C# Accessing another objects script values
Hi, I'm new to using Unity. So far I've managed to learn quite a lot, but I've come across a problem, which i've attempted to look for solutions although none seem to work for me.
I have three objects. The player, a door, and a collision object. What i'm aiming for is, when a player walks over the collision object, the door will close.
Names of my objects: 1. Player = Player 2. Collision object = colision 3. Door = frontdoor
My door also has a prefab which is called innerdoor which will be the object with an animation to open. This innerdoor object has been referenced by frontdoor by a script value. The value is called "doorInside".
I've tried the following
Frontdoor = GameObject.Find ("frontdoor");
Innerdoor = GameObject.Find (Frontdoor.doorInside);
Frontdoor.doorInside.GetComponent<Animation>().Play("Close");
So Frontdoor is the name of the whole door object. doorInside is a value from a script which references the actual object that the animation is on which is called innerdoor
Sorry if this has been a terrible explanation, hopefully someone can help though.
Thankyou
Answer by OctoMan · Sep 27, 2016 at 02:31 PM
First make sure your player has a rigidbody component & collider.
Also show us the complete copy of your OnTriggerEnter() function which might be on your trigger of the door.
The OnTriggerEnter works fine, its just I'm unsure how to access another objects scripts
This got asked i bet 100mio + times. You need to get the component of whatever you hit for example:
if(other.tag == "door"")
{
other.gameObject.GetComponent<DoorScript>().valueToChange = iDont$$anonymous$$now.
}
$$anonymous$$ake sure the values you want to access are public. Same for functions and so on.
I'm having troubles with the GetComponent, because the script i'm trying to access which is on a different object keeps on co$$anonymous$$g up saying the type or namespace cannot be found.
I'm using this:
objectname = GameObject.Find ("Frontdoor");
objectname.GetComponent<DynamicObject>().locked = true;
Here is an image of what Frontdoor looks like. So what i'm pretty much trying to do is change that Locked to true by a script that is running on a different object
Please post your whole OnTriggerEnter Function, otherwise i can't help. It seems you do something i don't see.
This is my whole OnTriggerEnter function
void OnTriggerEnter(Collider col)
{
if (col.tag == "Player")
{
objectname = GameObject.Find ("Frontdoor");
objectname.gameObject.GetComponent<DynamicObject>().locked = true;
currentobject = GameObject.Find ("closeFrontdoor");
Destroy(currentobject);
}
}