- Home /
How can I access values from a component script in another object
I have a very simple scene with a single cube, a camera and a light. I've written a C# class which processes user input swipe gestures from either touches or from the mouse, and also for specific regions of the screen.
I've attached the script twice as components of the camera. One to service swipes on the left hand side and one to service swipes on the right (there is a long drawn out reason for this that I won't go into here). All works fine and the scripts function as expected.
I'd now like to move the cube in the direction of the swipe, but can't figure out how I can get the values from the swipe controllers (attached to the camera) to the code which animates the cube.
In short, (as titled) - how can I access values from my swipe controller scripts in my cube controller script. Also, if you have the same script attached to the same object more than once, how does Unity differentiate between the two?
Hope that makes sense, Many thanks,
I'm surprised you didn't either google this or use the Search field, above. This gets asked several times per day, every day, for the last 5 years.
I'm more surprised that you actually think I didn't. If I'd found anything that worked, I wouldn't be posting here. This page didn't seem to help much. I know how to access a script of a specific type, but not when it's set as a component of another object.
http://answers.unity3d.com/questions/11601/can-i-have-multiple-components-of-the-same-type-on.html
There are a thousand examples and you gave no indication you looked or tried any.
Yes, but part of the problem is that if you don't know what you're looking for - it's hard to find the right question. At this stage, I don't even know if the question I posted is the right ter$$anonymous$$ology. Only started unity this morning.
Answer by origonn · Apr 05, 2014 at 06:54 PM
To find the scripts from a different object, just do
GameObject.Find("GameObjectName").GetComponents<Script>();
This will return an array of Script types, at which point its up to you to figure out which one the [0] and [1] elements refer to. Unless you change the order in the editor however, the order should always be the same
Finally, this put me on the right track (in combination with 'Camera.main'). Thank you!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Problems with Audio Sources 1 Answer
Distribute terrain in zones 3 Answers