我定义了一个类Item
public class Item : MonoBehaviour
{
public int ID { get; set; }
public string Name { get; set; }
public ItemType Type { get; set; }
public string Description { get; set; }
public int SellPrice { get; set; }
public int BuyPrice { get; set; }
public Sprite Sprite { get; set; }
public Item(int _id,string _name,ItemType _type,string _description,int _sellprice,int _buyprice,Sprite _sprite)
{
this.ID = _id;
this.Name = _name;
this.Type = _type;
this.Description = _description;
this.SellPrice = _sellprice;
this.BuyPrice = _buyprice;
this.Sprite = _sprite;
}
public Item()
{
this.ID = -1;
}
}
然后实例化出来一个item对象
Item temp=new Item(
(int)jsonData[i]["id"],
jsonData[i]["name"].ToString(),
(ItemType)System.Enum.Parse(typeof(ItemType),
jsonData[i]["type"].ToString()),
jsonData[i]["description"].ToString(),
(int)jsonData[i]["sellprice"],
(int)jsonData[i]["buyprice"],
Resources.Load<Sprite>(jsonData[i]["sprite"].ToString())
用Debug.Log(temp==null);语句判断出来的结果是true,也就是对象为空,但是Debug.Log(temp.Description);语句输出对象的属性又能够得到正确信息。
请问有没有大佬知道原因??求告知,谢谢
== null的判断是类似于C 类重载了==运算符。你new出来的对象实际是有的,因为是无效的所以== null为true。
继承MonoBehaviour的脚本不能用new关键词创建对象,如果你只是想做数据类的话,不要继承MonoBehaviour,如果要继承MonoBehaviour就只能用AddComponent创建对象。
你 Debug.Log(temp==null)的时候应该在temp这个对象创建之前,或者是temp这个对象是一个局部变量。访问不到。