【发布时间】:2021-02-22 00:47:57
【问题描述】:
我正在 Unity 中制作 C# 脚本。我的意图是创建一个类Scenario,创建代表不同场景的类,然后将其存储在数组scenarioListAll中。
代码的一个(简化)版本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OverallManager2 : MonoBehaviour
{
public static object[] scenarioListAll = new object[40];
public class Scenario
{
public string scenarioDesc;
public bool surprise; // The 'surprise' bool I want to reference is defined here
public string surpriseType;
public int[] leftOption;
public int[] rightOption;
public int scenarioNumber;
public Scenario(string st, bool sp, int[] l, int[] r, int n)
{
scenarioDesc = st;
surprise = sp;
leftOption = l;
rightOption = r;
scenarioNumber = n;
}
// I haven't used this, but I'm not sure if this matters so I'm including this too
public Scenario(string st, bool sp, string spt, int[] l, int[] r, int n)
{
scenarioDesc = st;
surprise = sp;
surpriseType = spt;
leftOption = l;
rightOption = r;
scenarioNumber = n;
}
}
public static int[] getArray(int a, int b, int c, int d, int e, int f)
{
int[] arr = new int[6] {a, b, c, d, e, f};
return arr;
}
// Storing scenarios, am looking for the bool (2nd position)
public Scenario s1 = new Scenario("Test1", false, getArray(1, 1, 1, 1, 1, 1), getArray(1, 1, 1, 1, 1, 1), 1);
public Scenario s2 = new Scenario("Test2", true, getArray(1, 1, 1, 1, 1, 1), getArray(1, 1, 1, 1, 1, 1), 2);
public Scenario s3 = new Scenario("Test3", false, getArray(1, 1, 1, 1, 1, 1), getArray(1, 1, 1, 1, 1, 1), 3);
void Awake()
{
// Store scenarios in object array
scenarioListAll[0] = s1;
scenarioListAll[1] = s2;
scenarioListAll[2] = s3;
for(int i = 0; i < 40; i++)
{
object temp = scenarioListAll[i]; // Trying to extract the object stored in the array in a temp object
bool surpriseCheck = temp.surprise; // I am having problems with this line
if(surpriseCheck == true)
{
// Do something
}
}
}
// Ignoring start and update since they're irrelevant in this context
}
我想做的是检查新定义的场景(例如s1)中的surprise元素是否为真。为此,我计划提取存储在数组scenarioListAll 中的场景,然后从那里提取surprise 组件。但是,我不知道如何执行此操作(例如,在上面显示的代码中,它返回编译器错误 CS1061)。
我认为我也找不到任何关于此的文档,但我可能没有理解某些内容。我是自学,所以请多多包涵我的知识/演示文稿。
感谢您的宝贵时间。非常感谢您的帮助。
【问题讨论】:
-
object没有.surprise属性。也许您应该将数组定义为public static Scenario[] scenarioListAll和temp为Scenario temp = scenarioListAll[i];?为什么在这些情况下使用object? -
对不起@Rufus L,我对此不好。我没有意识到我可以直接为
Scenario使用数组。不过问题已经解决了,感谢您的意见。