- Home /
Caching Transform Javascript Help
I'm fairly new to using Javascript, have been using C#. I've had a couple of null reference issues when trying to cache components into a class-scoped variable. Like this for example:
var tran : Transform;
function Start()
{
tran = transform;
}
function IAtePestoForLunch()
{
var go : GameObject = new GameObject();
go.transform = tran; // <--- NULL tran
}
I'm wondering if this is okay to do first of all. I was doing this fine in C#. Otherwise I think the issue is how I create the object and add the script. I have a gameobject I created on the fly with 'new GameObject()'. I then AddComponent a script (like above) to it. Is it possible that the Start() function is not run when the script component is added after Instantiation? Or should the Start function run upon adding it as a component? Should I be adding component before Instantiation somehow and how would I do that without using a prefab? Thank you
"tran" sucks. Use C# and call it "new Transform transform", utilizing base.transform.
What kind of answer is that. I have to use javascript. Easier to $$anonymous$$ch the young folk.
There is a unique relationship between a gameObject and a transform. One cannot exist without the other.
A gameObject always has a transform, and a transform is always in reference to its own gameObject.
I'm sure the Start is running and tran is populated. This can easily be checked by looking in the inspector when you run this. Look and see what appears in the inspector for tran.
So, when you create a new gameObject it already comes with a transform component.
What are you trying to do here?
go.transform.position = tran.position;
Instantiate ( tran, ...... );
In another script I'm saying something like this:
var go : GameObject = new GameObject()
go.AddComponent(ScriptFromOriginalPostAbove);
go.GetComponent(ScriptFromOriginalPostAbove).IAtePestoForLunch();
The tran variable is null as if the Start function didn't run. I add the component after I create a new gameobject.
Your answer
Follow this Question
Related Questions
Simple Instantiate gameObject problem 3 Answers
[JS] transform.rotation not working 1 Answer
How can i Limit the Mouse X Axis for Mouse Look 3 Answers
Component's transform 1 Answer