- Home /
get script of another gameobject in c#
i have a script attached to my main camera (named mainScript, in c#) which i want to access with another script (c#).
it should be as easy as Camera.main.GetComponent(mainScript)
but this throws out the following errors:
error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected
error CS1502: The best overloaded method match for `UnityEngine.GameObject.GetComponent(System.Type)' has some invalid arguments
error CS1503: Argument `#1' cannot convert `object' expression to type `System.Type'
on the other hand,`Camera.main.GetComponent ("Main Script")` works but then adding .function or .variable throws out
error CS1061: Type `UnityEngine.Component' does not contain a definition for `midFlight' and no extension method `midFlight' of type `UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
im really confused atm as i dont get what im doing wrong and i already used these without problem in js code
Camera.main.GetComponent < mainScript >();
I had to add spaces in because formatting removed text otherwise.
Answer by robertbu · May 16, 2014 at 02:53 PM
It is easiest to use the generic version of GetComponent in C#:
Camera.main.GetComponent<mainScript>();
You could also do:
Camera.main.GetComponent(typeof(mainScript));
Your answer
Follow this Question
Related Questions
How to run a function in a GO that have DontDestroyOnLoad 1 Answer
Move gameobject pivot 6 Answers
Distribute terrain in zones 3 Answers
C# GetComponent / change values throught other script 3 Answers