- Home /
A Silly simple question about scope
I am trying to add a LineRenderer to an object during runtime using script, so I can visualize a vector. I can add the component just fine, but I can't seem to access sub components from the component after creating it and I can't figure out why.
private var line:Component;
function Start () {
line = gameObject.AddComponent(LineRenderer);
}
function Update () {
line.SetPosition(0,transform.position);
line.SetPosition(1,transform.up*-2);
}
With this code I get the error "'SetPosition' is not a member of 'UnityEngine.Component'"
What am I doing wrong? It must be a simple mistake.
Answer by CHPedersen · Sep 12, 2012 at 06:54 AM
This occurs because AddComponent returns Component, it does not return an object of type LineRenderer. To get access to the methods you want, you have to declare the line as a LineRenderer in the top there, instead of Component:
private var line:LineRenderer;
The types should match just fine, because LineRenderer inherits from Renderer, which in turn inherits from Component, so a LineRenderer is a Component.
It makes so much sense now, thank you. I didn't understand what the error message was really telling me. It was quite clear what was wrong all along.
Learning Unity and Java at the same time has so far proven ... challenging, but increasingly encouraging.
Your answer
Follow this Question
Related Questions
Trying to child multiple GameObjects to one master object in script 1 Answer
How Do I Get a Script to Reference the GameObject When Using AddComponent? 1 Answer
Adding same Type to gameObject.AddComponent repeatedly keeps modifying first component. 2 Answers
What is happening when you use greater and lass than signs with AddComponent? 1 Answer