UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create a square at mouse position with a random colour from a gradient"
using UnityEngine; public class SquareSpawner : MonoBehaviour { public Gradient colorGradient; public GameObject squarePrefab; private Camera mainCamera; void Start() { mainCamera = Camera.main; } void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 mousePosition = Input.mousePosition; mousePosition.z = 10f; Vector3 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition); GameObject square = Instantiate(squarePrefab, worldPosition, Quaternion.identity); Renderer squareRenderer = square.GetComponent<Renderer>(); float randomValue = Random.Range(0f, 1f); Color randomColor = colorGradient.Evaluate(randomValue); squareRenderer.material.color = randomColor; } } }