- Home /
GetComponent Errors
Hello there, I had been struggling with unitys GetComponent for quiet some time now.
Code:
ScriptABC abc = (ScriptABC) collidedObject.collider.gameObject.GetComponent(typeof(ScriptABC));
When i use the above line in collision detection code, all i get is the below error :(
Cannot convert type 'UnityEngine.Component' to 'ScriptABC'
ScriptABC is not a Monobehavior and I want to access some methods exposed in that script.
abc.GetLife() and so on
This error doesnt leave me to proceed !
Any ideas?
Thanks folks!
Well, if ScriptABC is not a $$anonymous$$onoBehaviour, then it cannot be a component added to your object, is it not? This will explain why you get the error. There is probably a workaround, but you will have to tell us where this ScriptABC object is (is it a field, for example, of the collider?)
Answer by Statement · Mar 07, 2011 at 10:15 PM
Make sure your ScriptABC really inherits from MonoBehaviour.
class ScriptABC : MonoBehaviour
{
//...
}
Answer by Wolfram · Aug 20, 2010 at 09:38 AM
Lose the typeof().
UnityScript:
ScriptABC abc = collidedObject.collider.gameObject.GetComponent(ScriptABC);
C#:
ScriptABC abc = collidedObject.collider.gameObject.GetComponent<ScriptABC>();
Nope , that wont work. It says ScriptABC is not of type Component. GetComponent needs the parameters to be of type UnityEngine.Component.
The exact error is :
Error 1 The type 'ScriptABC' cannot be used as type parameter 'T' in the generic type or method 'UnityEngine.GameObject.GetComponent()'. There is no implicit reference conversion from 'ScriptABC' to 'UnityEngine.Component'
Oh, I overlooked your "ScriptABC is not a $$anonymous$$onobehavior" part. Only scripts derived from $$anonymous$$onoBehaviour can be attached to GameOBjects, and will be recognized as Components.
Your answer
Follow this Question
Related Questions
GetComponent of copies of one gameobject? 0 Answers
How to get script component of an object with out using its name? 2 Answers
Help with accessing scoring system variable C# plz. 3 Answers
FindGameObjectsWithTag Changing Variable on Another Script Not Fully Working 2 Answers
Referencing booleans from settings 1 Answer