how to change background by click the screen in Unity 2D, please show me the code
时间: 2023-11-22 16:56:24 浏览: 76
Here's an example code snippet that changes the background color of a Unity 2D game when the user clicks on the screen:
```csharp
using UnityEngine;
public class BackgroundColorChanger : MonoBehaviour
{
private Camera mainCamera;
private void Awake()
{
mainCamera = Camera.main;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
ChangeBackgroundColor();
}
}
private void ChangeBackgroundColor()
{
float red = Random.Range(0f, 1f);
float green = Random.Range(0f, 1f);
float blue = Random.Range(0f, 1f);
mainCamera.backgroundColor = new Color(red, green, blue);
}
}
```
This script should be attached to a GameObject in your scene, and it will detect when the user clicks the left mouse button. When this happens, the `ChangeBackgroundColor()` method is called, which generates a random RGB color and sets it as the background color of the main camera. You can modify the `ChangeBackgroundColor()` method to change the background in any way you like.
阅读全文