- Home /
Code Problem
PLS Help Me I get these 4 errors :
UnityException: You are not allowed to call this function when declaring a variable. Move it to the line after without a variable declaration. If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function. WeaponSys..ctor ()
FindGameObjectWithTag can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
ArgumentException: FindGameObjectWithTag can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. WeaponSys..ctor ()
NullReferenceException WeaponSys.Update () (at Assets/WeaponSys.cs:23)
using UnityEngine; using System.Collections;
public class WeaponSys : MonoBehaviour {
GameObject weapon = GameObject.FindGameObjectWithTag("weaponpos");
GameObject ak47 = GameObject.FindGameObjectWithTag ("ak47");
int curPrimary = 0;
public int Primary = 0;
int Secondary = 0;
int Melee = 0;
// Update is called once per frame
void Update () {
switch(Primary) {
case 1:
if (curPrimary == 1)
{
}
else
{
Object.Instantiate(ak47,weapon.transform.position,Quaternion.identity);
curPrimary = 1;
}
break;
}
}
}
Have you read the errors? They tell you exactly how to fix the situation.
Answer by ProfilerOne · Feb 23, 2014 at 09:06 PM
Try this:
public class WeaponSys : MonoBehaviour {
GameObject weapon;
GameObject ak47;
int curPrimary = 0;
public int Primary = 0;
int Secondary = 0;
int Melee = 0;
void start() {
weapon = GameObject.FindGameObjectWithTag("weaponpos");
ak47 = GameObject.FindGameObjectWithTag ("ak47");
}
// Update is called once per frame
void Update () {
switch(Primary) {
case 1:
if (curPrimary == 1)
{
}
else
{
Object.Instantiate(ak47,weapon.transform.position,Quaternion.identity);
curPrimary = 1;
}
break;
}
}
}
Converted post as later duplicate answer
You cannot do this in Unity: GameObject weapon = GameObject.FindGameObjectWithTag("weaponpos");
That line cannot be called during $$anonymous$$onoBehavior
class construction, because Unity handles this part. And nothing about GameObject.
is guaranteed/defined/available at that point.
Ins$$anonymous$$d do just
GameObject weapon;
without initialization and
void Start()
{
weapon = GameObject.FindGameObjectWithTag("weaponpos");
//...
}
Or better yet, just make it public GameObject weapon;
and drag&drop the object in the inspector to that variable in Unity itself (assu$$anonymous$$g the object is in scene and not created dynamically).