c#中关于Object reference not set to an instance of an object物体未实例化的一个问题

1 篇文章 0 订阅

浅浅记录一下在写c#脚本过程中遇到的一个实例化问题

在编写中,本想着使用Vector3类创建一个三维矩形数组来储存地图中的一些位置,代码如下

public static int R =3, C=5, R1=3, C1=3;
public static Vector3[ , , ] Points;

for (int y = 9 - C1; y > 9 - m * R - C1;y = y - m)
        {
            for (int x = -17 + R1; x < -17 + n * C + R1; x= x + n )
            {
               for(int i = 0;i < R; i++)
                {
                    for(int j = 0; i < C; j++)
                    {
                        Points[i, j, 0] = new Vector3 (x, y, 0);
                        Points[i, j, 1] = new Vector3 (x+1, y, 0);
                        Points[i, j, 2] = new Vector3 (x, y-1, 0);
                        Points[i, j, 3] = new Vector3 (x+1, y-1, 0);
                    }
                }
            }
        }

但是发现我只声明了Vector3数组,并没有实例化,导致脚本在unity中运行时出错

 解决这个问题的关键就是要在数组声明的同时进行实例化

public static int R =3, C=5, R1=3, C1=3;

public static Vector3[ , , ] turnPoints=new Vector3[R, C, 4];

然后就不会报错了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
"Object reference not set to an instance of an object" 是一个常见的错误,它表示你尝试访问一个初始的对象或者空引用。 这种错误通常发生在以下几种情况下: 1. 你在使用一个初始的变量。在使用变量之前,需要确保将其实例。例如: ```csharp string myString; Console.WriteLine(myString); // 这里会报 Object reference not set to an instance of an object 错误 // 正确做法: string myString = "Hello"; Console.WriteLine(myString); ``` 2. 你调用了一个返回 null 值的方法或属性,并试图对其进行操作。在使用方法或属性返回的结果之前,需要检查其是否为 null。例如: ```csharp string myString = GetStringFromDatabase(); // 假设该方法返回 null int length = myString.Length; // 这里会报 Object reference not set to an instance of an object 错误 // 正确做法: string myString = GetStringFromDatabase(); if (myString != null) { int length = myString.Length; } ``` 3. 在访问对象的属性或方法时,对象本身为 null。在使用对象之前,需要确保对象不为 null。例如: ```csharp MyClass myObject = null; myObject.DoSomething(); // 这里会报 Object reference not set to an instance of an object 错误 // 正确做法: MyClass myObject = new MyClass(); myObject.DoSomething(); ``` 请检查你的代码,找到引发错误的位置,并确保对象已经初始或者不为 null。如果你还需要更多帮助,请提供出错的代码片段,我将尽力帮助你解决问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yupl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值