如何在 Unity 的另一个场景中访问游戏对象 [重复]

Posted

技术标签:

【中文标题】如何在 Unity 的另一个场景中访问游戏对象 [重复]【英文标题】:How can i access game object in another scene in Unity [duplicate] 【发布时间】:2018-06-21 00:35:45 【问题描述】:

我是 Unity 的初学者,所以...

我想改变另一个场景中的游戏对象的精灵,那不是我正在使用的那个

这是第一个场景的代码,我想获取带有标签“iman”的游戏对象,到第二个场景

public class Gravidade : Move


void OnEnable ()

    rigid = GetComponent<Rigidbody2D> ();

// Use this for initialization
void Start ()

    efeito.SetActive (false);
    iman_pos = GameObject.FindGameObjectWithTag ("iman").transform.position;
    imanbase_pos = GameObject.FindGameObjectWithTag ("imanbase").transform.position;

    targetRotation = transform.rotation;
    vidas = 3;

    coins = 0;
    //vidas_text = GetComponent<Text>();

    //GUIText vidas_text = GameObject.FindWithTag("vidas").GetComponent<GUIText>() as GUIText;

    rend = GetComponent<Renderer> ();


// Update is called once per frame

void Update ()


    backgrounds = GameObject.FindGameObjectsWithTag ("background");
    obstaculos = GameObject.FindGameObjectsWithTag ("obstaculos");
    allcoins = GameObject.FindGameObjectsWithTag ("coins");
    allvidas = GameObject.FindGameObjectsWithTag ("vidas123");
    powerups = GameObject.FindGameObjectsWithTag ("powerup");



    float dist = 1 / (iman_pos.y - imanbase_pos.y - 2);


    bool space = Input.GetKeyUp ("space");



    if (/*Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended */ space && vidas > 0 && lose == false) 
        PlaySound (0);
        magnetismo = !magnetismo;
        targetRotation *= Quaternion.AngleAxis (180, Vector2.left);
        lose_text.text = "";
    


    transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation, 10f * 0.5f * Time.deltaTime); 


    if (magnetismo) 
        velocity += gravityModifier * Physics2D.gravity * Time.deltaTime - (dist * dist * Physics2D.gravity * amplitudeOsc);
        rigid.velocity = velocity;
        //nbTouches = 0;

     else 
        velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
        rigid.velocity = velocity;
        //nbTouches = 0;
    



    if (Mathf.Abs (velocity.y) > maxVelocity) 
        velocity.Normalize (); 
        velocity = velocity * maxVelocity;
    

    //Debug.Log(velocity);

    if (iman_pos.y + 2.5f < imanbase_pos.y + 0.8f)
        iman_pos.y = imanbase_pos.y;

    if (iman_pos.y + 2.5f > tecto.y + 2.5f)
        iman_pos.y = imanbase_pos.y;

    //Time.timeScale = 0;

    //rigid.velocity = velocity;
    //Debug.Log (dist);




/*private void OnCollisionEnter2D(Collision2D collision)

    //Debug.Log ("Perdeste!!");
    //Time.timeScale = 0;
*/

void OnTriggerEnter2D (Collider2D other)

    if (other.tag == "coins") 
        PlaySound (3);
        Destroy (other.gameObject);
        coins = coins + 1;
        coins_text.text = "x" + coins;

    

    if (other.tag == "obstaculos" && bater == true) 
        //Destroy (other.gameObject);
        if (vidas > 0) 
            PlaySound (1);
            vidas = vidas - 1;
            vidas_text.text = "x" + vidas;
            //Debug.Log (vidas);
            Destroy (other.gameObject);
            BlinkPlayer (3);
            if (vidas == 0) 
                PlaySound (2);
                Time.timeScale = 0;
                losemenu.SetActive (true);
                //SceneManager.LoadScene (0);
            
        
    

    if (other.tag == "imanbase" || other.tag == "tecto") 
        lose = !lose;
        PlaySound (2);
        Time.timeScale = 0;
        losemenu.SetActive (true);
        //SceneManager.LoadScene (0);
    

    if (other.tag == "vidas123") 
        PlaySound (4);
        vidas = vidas + 1;
        vidas_text.text = "x" + vidas;
        Destroy (other.gameObject);
    

    if (other.tag == "passar nivel") 
        Time.timeScale = 0;
        lose_text.text = "Victory!";
        //SceneManager.LoadScene (0);
    
    if (other.tag == "powerup") 
        Destroy (other.gameObject);
        StartCoroutine (pw ());
    




void PlaySound (int clip)

    GetComponent<Audiosource> ().clip = audioClip [clip];
    GetComponent<AudioSource> ().Play ();


void BlinkPlayer (int numBlinks)

    StartCoroutine (DoBlinks (numBlinks, 0.2f));


IEnumerator DoBlinks (int numBlinks, float seconds)

    for (int i = 0; i < numBlinks * 2; i++) 
        rend.enabled = !rend.enabled;
        yield return new WaitForSeconds (seconds);
    

    rend.enabled = true;



IEnumerator pw ()


    float timePassed = 0;
    while (timePassed < 3) 
        efeito.SetActive (true);
        bater = false;
        foreach (GameObject back in backgrounds) 
            back.GetComponent<Move> ().speed = 15.0f;
        
        foreach (GameObject obs in obstaculos) 
            obs.GetComponent<Move> ().speed = 15.0f;
        
        foreach (GameObject ac in allcoins) 
            ac.GetComponent<Move> ().speed = 15.0f;
        
        foreach (GameObject vd in allvidas) 
            vd.GetComponent<Move> ().speed = 15.0f;
        
        foreach (GameObject pu in powerups) 
            pu.GetComponent<Move> ().speed = 15.0f;
        

        timePassed += Time.deltaTime;
        //Debug.Log (timePassed);
        yield return null;
    
    efeito.SetActive (false);
    bater = true;
    foreach (GameObject back in backgrounds) 
        back.GetComponent<Move> ().speed = 3.0f;
    
    foreach (GameObject obs in obstaculos) 
        obs.GetComponent<Move> ().speed = 3.0f;
    
    foreach (GameObject ac in allcoins) 
        ac.GetComponent<Move> ().speed = 3.0f;
    
    foreach (GameObject vd in allvidas) 
        vd.GetComponent<Move> ().speed = 3.0f;
    
    foreach (GameObject pu in powerups) 
        pu.GetComponent<Move> ().speed = 3.0f;
    

这是第二个场景中第二个脚本的代码,我想在其中更改精灵

public class MainMenu : MonoBehaviour

public GameObject menustore;
public Sprite skinteste;


public void PlayGame ()

    SceneManager.LoadScene (1);
    Time.timeScale = 1f;

public void Home1()
    SceneManager.LoadScene (0); 


public void openstore ()

    menustore.SetActive (true);


public void skin1 ()

    //DontDestroyOnLoad (GameObject.FindWithTag("iman"));
    GameObject.FindWithTag("iman").GetComponent<SpriteRenderer>().sprite 
= skinteste;

【问题讨论】:

我几乎可以肯定它是重复的,我只是找不到它 access a GO in another scene 其他场景的GO不存在,所以不能。 这里有两个重复,但还有更多。 [1]:***.com/questions/22837395/… [2]:***.com/questions/49637298/… 【参考方案1】:

您必须使用 Unity3d 为您提供的DontDestroyOnLoad() 方法。使用这种方法,您可以创建在从场景切换到场景时不会被破坏的游戏对象。

public class YourClass : MonoBehaviour 

public static YourClass singleton = null;

void Awake()

     DontDestroyOnLoad(this.gameObject);
     if(singleton == null)
     
         singleton = this;
      

还可以看看它经常使用的单例设计模式。 :)

【讨论】:

这是一个糟糕的代码示例。如果您在加载另一个场景后在不同场景中有多个单例对象,那么您最终将使用 DDOL 获得多个悬空的单例对象。最好找一个使用锁和销毁方法的统一单例示例 @Herrgott 这绝不是糟糕的代码。这实际上取决于用例。是的,如果您想在场景中来回切换,这不是最合适的。但是对于预加载将被反复访问的共享资源就很好了。

以上是关于如何在 Unity 的另一个场景中访问游戏对象 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何访问另一个场景中存在的游戏对象[重复]

从 Unity 中的不同场景访问变量

我需要使用 c# 将一个游戏对象旋转到 Unity 中的另一个游戏对象,但我希望旋转仅在 z 中

如何通过 GetComponent 从另一个游戏对象中的另一个脚本访问变量?

如何在unity3d中将2d对象导入场景3d

如何通过脚本在 Unity 中重新定位和调整游戏对象的大小?