Unity随机小技巧

本文介绍使用Unity实现随机位置生成和随机颜色选择的方法。通过CircleRd和SphereRd两个脚本,演示如何在圆内和球体内随机生成物体,并为每个物体赋予随机颜色。适用于游戏开发中需要随机元素的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Color Random.ColorHSV() 颜色随机
  • Vector3 Random.insideUnitCircle 圈内位置随机
  • Vector3 Random.insideUnitSphere 球体内位置随机
    在这里插入图片描述
public class CircleRd : MonoBehaviour
{
    [SerializeField] GameObject prefab;
    [Range(0, 10), SerializeField] float radius = 5.0f;

    void Update()
    {
        if (Input.GetKey(KeyCode.C))
            InsideCircle();
    }

    void InsideCircle()
    {
        GameObject newCube = Instantiate(prefab);
        newCube.transform.SetParent(transform);
        Vector2 randomPos = Random.insideUnitCircle;
        Vector3 newRandomPos = new Vector3(randomPos.x, 0, randomPos.y);
        newCube.transform.localPosition = newRandomPos * radius;
        newCube.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
    }
    void DrawCircle()
    {
        Gizmos.color = Color.white;
        float theta = 0;
        float x = radius * Mathf.Cos(theta);
        float y = radius * Mathf.Sin(theta);
        Vector3 pos = transform.position + new Vector3(x, 0, y);
        Vector3 newPos = pos;
        Vector3 lastPos = pos;
        for (theta = 0.1f; theta < Mathf.PI * 2; theta += 0.1f)
        {
            x = radius * Mathf.Cos(theta);
            y = radius * Mathf.Sin(theta);
            newPos = transform.position + new Vector3(x, 0, y);
            Gizmos.DrawLine(pos, newPos);
            pos = newPos;
        }
        Gizmos.DrawLine(pos, lastPos);
    }

    void OnDrawGizmos()
    {
        DrawCircle();
    }
}
public class SphereRd : MonoBehaviour
{
    [SerializeField] GameObject prefab;
    [Range(0, 10), SerializeField] float radius = 5.0f;

    void Update()
    {
        if (Input.GetKey(KeyCode.S))
            InsideSphere();
    }

    void InsideSphere()
    {
        GameObject newCube = Instantiate(prefab);
        newCube.transform.SetParent(transform);
        newCube.transform.localPosition = Random.insideUnitSphere * radius;
        newCube.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
    }
    void DrawSphere()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, radius);
    }

    void OnDrawGizmos()
    {
        DrawSphere();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值