- Home /
Instantiate in a class
Hi, I am farely new to Unity but am having problems with some scripting in Javascript.
I am trying to instantiate and object of a prefab in a class. My current code is as follows:
class unitLine { public var soldierPre : Transform;
function unitLine()
{
GameObject.Instantiate(soldierPre);
}
};
var Line1 : unitLine;
function Awake() { Line1 = new unitLine(); }
This gives the error "ArgumentException: The thing you are trying to instantiate is null". I have the prefab object applied in the hierachy and not the script itself.
I have searched for more than 2 hours trying to find a solution, but just keep error hopping.
I am also having some problems tryingto access a global variable in my class. Is it possible?
Many thanks to those who can help.
Answer by Jessy · Feb 18, 2011 at 08:15 PM
soldierPre is serialized within Line1. When you create a new unitLine, the soliderPre of that unitLine is null. I don't know what you're actually doing, but this could work:
(Your capitalization does not adhere to standards so I modified that.)
class UnitLine { var soldierPre : Transform;
function UnitLine (soldierPre : Transform) {
this.soldierPre = soldierPre;
UnityEngine.Object.Instantiate(soldierPre);
}
}
var line1 : UnitLine;
function Awake() { line1 = UnitLine(line1.soldierPre); }
I tried defining soldierPre as a global variable above the class but I could not find a way to access it within the class. Any ideas?
I have no idea what you're doing, but the code above works, at least. Describe what you actually want to do, ins$$anonymous$$d, because this code looks useless.
Thanks that code worked fine. I completely forgot about passing the constructor an argument of the transform object. Stupid mistake.
Your answer
Follow this Question
Related Questions
c# Unexpected symbol '=' in struct, class..... 1 Answer
Using JS class in C# 1 Answer
Scripting errors only when building for iPhone 2 Answers
Enemy not spawning correctly 1 Answer