C# 如何通过了解自定义类中的变量来访问该类?

C# 如何通过了解自定义类中的变量来访问该类?,c#,class,unity3d,C#,Class,Unity3d,我创建了一个自定义类: using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Obstacle { public GameObject gameObj; public Color color; public GameObject starExplosion; public GameObje

我创建了一个自定义类:

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

[System.Serializable]
public class Obstacle {
    public GameObject gameObj;
    public Color color;

    public GameObject starExplosion;
    public GameObject regular_Trail;
    [HideInInspector]
    public bool firstCollistion = true;

    public static Vector3 SpawnLocation()
    {
        int positionQuadran = Random.Range(1, 3);
        switch (positionQuadran)
        {
            //spawn above the player
            case 1:
                 return new Vector3(Random.Range(1.5f, -1.5f),
                                                      Random.Range(4f - SpawnStars.closerToPlayer, 4.5f),
                                                      Random.Range(1, -3.2f));
            //spawn benith the player
            case 2:
                return new Vector3(Random.Range(1.5f, -1.5f),
                                                      Random.Range(-0.5f, SpawnStars.closerToPlayer),
                                                      Random.Range(1f, -3.2f));
        }
        return Vector3.zero;
    }
}
现在,正如您在这个类中看到的,有一个变量
publicgameobjectgameobj
现在在另一个脚本中,我需要访问这个
gameObj
实例所在的
barrier
类的实例。我正试着这样做:

private void OnCollisionEnter(Collision collision)
{
    collision.collider. //what do I do next?
}
出于几个原因,我不想让
障碍
类继承自
单一行为
。既然我无法从场景中的另一个
GameObject
访问该类,那么我如何通过只知道
gameObj
变量来访问它

更新我将添加用于生成障碍物类的脚本:

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


public class SpawnStars : MonoBehaviour
{
    [SerializeField]
    private List<Obstacle> obstacles;
    [HideInInspector]
    public List<Obstacle> normalStarsPool = new List<Obstacle>();

    [SerializeField]
    private List<Obstacle> otherObstacles;
    [HideInInspector]
    public List<Obstacle> otherObstaclesPool;

    [SerializeField]
    private int spawnNumber = 2;

    private Obstacle nextObstacleToSpawn;
    [SerializeField]
    public GameObject panel;
    public static bool spawnNow = true;
    public static bool first_find_star = true;

    public static float starSpeed;
    /* this variables will make the stars to spawn closer and closer to the player as 
    the score  is progresing*/
    public static float closerToPlayer;
    private float spawnPositionZ;

    private void Start()
    {
        first_find_star = true;
        spawnNow = true;

        GeneratePrefabs(spawnNumber, obstacles, normalStarsPool);
        StartCoroutine(ShuffleList(normalStarsPool));

        GeneratePrefabs(2, otherObstacles, otherObstaclesPool);
        StartCoroutine(ShuffleList(otherObstaclesPool));
    }
    private void LateUpdate()
    {
        if (spawnNow)
        {
            spawnNow = false;
            if (first_find_star)
            {
                nextObstacleToSpawn = FindStar(normalStarsPool);
                first_find_star = false;
            }
            //spawn the current star
            int randomNumber = Random.Range(0, 100);
            if(randomNumber >= 20){
                nextObstacleToSpawn = FindStar(normalStarsPool);
            }
            else{
                Debug.Log("corrupt star");
                nextObstacleToSpawn = FindStar(otherObstacles);
            }
            SpawnStar(nextObstacleToSpawn);

        }
    }
    void GeneratePrefabs(int how_many, List<Obstacle> prefabList, List<Obstacle> poolList)
    {
        foreach (Obstacle prefab in prefabList)
        {
            for (int i = 0; i <= how_many; i++)
            {
                Obstacle go = new Obstacle
                {
                    gameObj = Instantiate(prefab.gameObj)
                };
                go.regular_Trail = go.gameObj.transform.GetChild(1).gameObject;
                go.starExplosion = go.gameObj.transform.GetChild(0).gameObject;
                go.color = prefab.color;
                go.gameObj.SetActive(false);

                //setap all the colors for the obstacle
                ParticleSystem ps = go.starExplosion.GetComponent<ParticleSystem>();
                ParticleSystem.MainModule psmain = ps.main;
                psmain.startColor = go.color;

                //setup the collor of a partycle system
                ps = go.starExplosion.GetComponent<ParticleSystem>();
                psmain = ps.main;
                psmain.startColor = go.color;

                psmain.startColor = go.color;

                go.gameObj.GetComponent<Renderer>().material.color = go.color;
                poolList.Add(go);
            }
        }
    }
    Obstacle FindStar(List<Obstacle> poolList)
    {
        while (true)
        {
            int randomIndex = Random.Range(0, poolList.Count);
            if (!poolList[randomIndex].gameObj.activeInHierarchy)
            {
                Color color = poolList[randomIndex].color;
                color.a = 0.5f;
                panel.GetComponent<Renderer>().material.color = color;
                return poolList[randomIndex];
            }
            else randomIndex = Random.Range(0, poolList.Count);
        }
    }
        void SpawnStar(Obstacle star)
    {
        star.firstCollistion = false;
        star.starExplosion.SetActive(false);
        star.regular_Trail.SetActive(true);
        star.gameObj.GetComponent<MeshRenderer>().enabled = true;
        ScaleDifficulty();
        star.gameObj.transform.position = Obstacle.SpawnLocation();
        star.gameObj.SetActive(true);
    }

    //Shuffle a list every 4 seconds, don't pus this in an update or something cuz it's a coroutine
    IEnumerator ShuffleList(List<Obstacle> list_to_Shuffle)
    {
        while (true)
        {
            yield return new WaitForSeconds(4f);
            for (int i = 0; i < list_to_Shuffle.Count; i++)
            {
                Obstacle temp = list_to_Shuffle[i];
                int randomIndex = Random.Range(i, list_to_Shuffle.Count);
                list_to_Shuffle[i] = list_to_Shuffle[randomIndex];
                list_to_Shuffle[randomIndex] = temp;
            }
        }
    }
    //this will scale the difficulty as the score get's higher and higher
    public void ScaleDifficulty()
    {
        if (Menu.score < 60)
        {
            //the speed of the star as the score goes up
            starSpeed = ((float)Menu.score / 30) + 1f;
            //how close relative to the player will the stars spawn in the x and y axis?
            closerToPlayer += Menu.score / 60;
           // Debug.Log(starSpeed);
        }
    }
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共类明星:单一行为
{
[序列化字段]
私人名单障碍;
[hideininstecpt]
公共列表normalStarsPool=新列表();
[序列化字段]
私人障碍;
[hideininstecpt]
公共列表otherObstaclesPool;
[序列化字段]
私有整数=2;
私人障碍物靠近Stacletospawn;
[序列化字段]
公共游戏对象面板;
公共静态bool spawnNow=true;
公共静态bool first\u find\u star=true;
公共静态浮动星速;
/*这些变量将使星星越来越靠近玩家
比分在上升*/
公共静态浮动播放器;
私人浮点数;
私有void Start()
{
第一个查找星=真;
现在=真;
GeneratePrefabs(产卵数、障碍物、法线起点);
start例程(shufflist(normalStarsPool));
生成默认值(2,其他障碍,其他障碍池);
startcroutine(shufflist(otherObstaclesPool));
}
私有更新()
{
如果(现在)
{
spawnow=false;
如果(第一个找到星)
{
nextObstacleToSpawn=FindStar(normalStarsPool);
第一个查找星号=假;
}
//产生当前恒星
int randomNumber=Random.Range(0,100);
如果(随机数>=20){
nextObstacleToSpawn=FindStar(normalStarsPool);
}
否则{
Debug.Log(“腐败之星”);
nextObstacleToSpawn=FindStar(其他障碍物);
}
产卵星(下一颗星辰);
}
}
void GeneratePrefabs(int-how_-many,List-prefabList,List-poolList)
{
foreach(预制列表中的障碍物预制)
{
对于(int i=0;i
现在在另一个脚本中,我需要访问这个gameObj实例所在的障碍类的实例

给定一个
障碍物
类的实例,你怎么知道它被
游戏对象
的实例引用?或者你怎么知道它只被一个
游戏对象引用?

除非有双向引用,
游戏对象
引用了
障碍物
障碍物
也引用了
游戏对象
,否则无法确定什么引用了
障碍物

现在在另一个脚本中,我需要访问这个gameObj实例所在的障碍类的实例

给定一个
障碍物
类的实例,你怎么知道它被
游戏对象
的实例引用?或者你怎么知道它只被一个
游戏对象引用?


除非有双向引用,
游戏对象
引用了
障碍物
障碍物
也引用了
游戏对象
,-没有办法确定什么引用了
障碍物

的实例简而言之,你不能。这不是你设置的方式。如果您需要全局访问该对象,则需要全局跟踪它。Unity提供了一种方法来实现这一点(基本上是),但您已经说过不想使用它。因此,您必须构建自己的


假设您有一组
障碍物
对象,例如
IList障碍物
,您可以通过
障碍物获得它。其中(o=>o.gameObj==myLocalGameObjReference)
。一个更好的解决方案是,假设您将此脚本按1:1的比例附加到每个
障碍
中,只需将
障碍
简单地注入到脚本中。查看依赖项注入(DI)框架喜欢帮助配置和管理依赖项。另一种选择是。就个人而言,我会选择DI而不是单例。单例一开始似乎更容易,但很快就会遇到麻烦。

简而言之,你不能。不是你设置的方式。如果你需要全局访问该对象,你需要Unity提供了一种实现这一点的方法(本质上是),但你已经说过你不想使用它。所以你必须建立自己的


假设您有一组
障碍物
对象,例如
IList障碍物
,您可以通过
障碍物获得它。其中(o=>o.gameObj==myLocalGameObjReference)
。一个更好的解决方案是,假设您将此脚本按1:1的比例附加到每个
障碍
中,只需将
障碍
简单地注入到脚本中。查看依赖项注入(DI)框架喜欢帮助配置和管理依赖项。另一种选择是。就个人而言,我会选择DI而不是单例。单例一开始似乎更容易,但很快就会遇到麻烦。

您在哪里创建
障碍
类的实例?我根据您的请求更新了问题:)使用gameobjects
GetComponent()void GeneratePrefabs(int how_many, List<Obstacle> prefabList, List<Obstacle> poolList)
{
    foreach (Obstacle prefab in prefabList)
    {
        for (int i = 0; i <= how_many; i++)
        {
            Obstacle go = new Obstacle
            {
                gameObj = Instantiate(prefab.gameObj)
            };
            go.regular_Trail = go.gameObj.transform.GetChild(1).gameObject;
            go.starExplosion = go.gameObj.transform.GetChild(0).gameObject;
            go.color = prefab.color;
            go.gameObj.SetActive(false);

            //setap all the colors for the obstacle
            ParticleSystem ps = go.starExplosion.GetComponent<ParticleSystem>();
            ParticleSystem.MainModule psmain = ps.main;
            psmain.startColor = go.color;

            //setup the collor of a partycle system
            ps = go.starExplosion.GetComponent<ParticleSystem>();
            psmain = ps.main;
            psmain.startColor = go.color;

            psmain.startColor = go.color;

            go.gameObj.GetComponent<Renderer>().material.color = go.color;
            poolList.Add(go);
        }
    }
}