I have a card game I’m working on and I’m testing out a function that will instantiate a prefab from a list of prefabs. I keep getting this error:
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.
UnityEngine.GameObject…ctor () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/UnityEngineGameObject.cs:448)
DisplayCard…ctor ()
Sayfunc…ctor ()
When I click on the error it wont take me to any line of code it just shows me the game object I have a script on. Here are the two scripts that are listed in the error:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Sayfunc : MonoBehaviour
{
int x = 0;
List<CardClass> NewDeck = new List<CardClass> ();
List<GameObject> Prefabs = new List<GameObject> ();
DisplayCard Display = new DisplayCard ();
GameObject Test = new GameObject();
Card Deck = new Card ();
PrefabList Prefab = new PrefabList ();
void Start()
{
Deck.AddToDB ();
Deck.DeckA ();
NewDeck = Deck.Change ();
Prefabs = Prefab.GetPrefab();
Test = Prefabs [x];
Instantiate ((Test) as GameObject);
Destroy (Test.gameObject);
}
void Update(){
if(Input.GetMouseButtonDown(0)){
Display.SetHand (NewDeck, Prefabs, x);
x++;
}
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DisplayCard : MonoBehaviour {
CardClass TempCard = new CardClass ();
GameObject Test1 = new GameObject ();
List<CardClass> NewHand = new List<CardClass> ();
int y;
int D;
public void SetHand(List<CardClass> Hand, List<GameObject> Prefabs, int S){
D = S;
NewHand = Hand;
TempCard = NewHand [D];
y = TempCard._CardID;
Destroy (Test1.gameObject);
Test1 = Instantiate (Prefabs [y]) as GameObject;
}
}
I have no idea what the problem is and everything I have read about this topic didn’t fix it for me. Please could someone show me why I keep getting this error.