Home > front end >  how to pass a gameobject through a non static class in unity
how to pass a gameobject through a non static class in unity

Time:10-13

I am making a game with Unity, and I am working on an inventory system, and what I am trying to do is create a class called Item which has all the necessary information and functions attached to create an item, and then it also has an object with it to use to create each item, this is the simple class so far

public class Item
{
  public Item(string name, GameObject obj)
  {
    //name to display in inventory
    String ItemName = name;
    //object to be shown in inventory slot
    GameObject ShownObj = obj;
  }
}

but when I try to use the object to create a new item, I pass through a unity game object and it gives me an error saying that you can't use a field initializer with a nonstatic class, how can I either fix this or get around it? here's how I tried using the class:

Public gameobject item;
public Item testItem = new Item("test item", item);

CodePudding user response:

You cannot call the Item constuctor outside of a function, when you pass in a non-static variable like your GameObject!

You are trying to declare & initialize the Item variable before at compiletime (because it's outside of a function), that's not possible for non-static stuff, because they can change.

But you can initialize it in Start which is called once. Just declare the reference as public variable and initialize it in Start.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemTest : MonoBehaviour
{
    // public Item item = new Item("test item", obj); // won't work!
    public GameObject obj;
    public Item item;
    // Start is called before the first frame update
    void Start()
    {
        item = new Item("test item", obj);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

public class Item
{
    String ItemName;
    //object to be shown in inventory slot
    GameObject ShownObj;
    public Item(string name, GameObject obj)
    {
        //name to display in inventory
        ItemName = name;
        //object to be shown in inventory slot
        ShownObj = obj;
    }
}

Note: If your Item constructor only had a String as constructor parameter, it would work just fine, because the string is completely defined at compiletime.

  • Related