单击按钮时,Unity更改不同资产的组件



我对Unity和c#都很陌生,但我目前有一款有两种不同背景的游戏,我想知道当点击按钮时,如何在两种背景之间切换——LightBackground和NightBackground,默认背景是LightBackground,当点击按钮后,使用NightBackbackground。我的想法是在点击按钮时更改NightBackground图层(排序顺序(的顺序,但在尝试许多事情时都没有成功。

目前,我已经制作了一个夜间/黑暗脚本,我已经将其放置在单击按钮中,它会更改夜间背景的排序顺序,但我如何才能使其同时更改LightBackground的排序顺序。此外,目前我有一个名为game Manager的游戏对象,它链接到Gameover Canvas,它显示我想要的按钮和重播按钮;但一旦点击按钮,背景就会发生变化,但一旦点击回放按钮,背景会回到LightBackground。

NightDark脚本:

public class NightDark : MonoBehaviour
{
public GameObject NightBackground;
// Start is called before the first frame update
void Start()
{
NightBackground.GetComponent<SpriteRenderer>().sortingOrder++;
}
// Update is called once per frame
void Update()
{
}
}

游戏管理员脚本:

public class GameManager : MonoBehaviour
{
public GameObject gameOverCanvas;
private void Start()
{
Time.timeScale = 1;
}

public void GameOver()
{
gameOverCanvas.SetActive(true);
Time.timeScale = 0;
}
public void Replay()
{
SceneManager.LoadScene(0);
}
}

在这里查看Game Manager和NightDark可能更容易。

如果你们中的任何人能提供一点点帮助,我将不胜感激,因为我现在真的很挣扎。再次感谢。

什么反对拥有一个单独的背景控制器,而只切换出背景中显示的SpriteSpriteRenderer.sprite属性

public class BackgroundController : MonoBehaviour
{
// Drag all these in via the Inspector
[Header("References")]
[SerielizeField] private SpriteRenderer backgroundRenderer;
[Header("Assets")]
[SerielizeField] private Sprite daySprite;
[SerielizeField] private Sprite nightSprite;    
// This is static so it keeps its value session wide also after
// reloading the scene
private static bool _isDay;
private void Start()
{
// inverts the _isDay -> starts as day the first time
SwitchBackground();
}
// This you call when the button is clicked
public void SwitchBackground()
{
// invert the flag
_isDay = !_isDay;
// chose the new sprite according to the flag
backgroundRenderer.sprite = _isDay ? daySprite : nightSprite;
}
}

最新更新