Unity3D 用脚本来操作游戏对象3(添加与修改组件)

组件包括脚本类、粒子类、物理类、声音类和渲染类等等。

添加游戏组件可以使用 AddComponent<组件名>() 的方法。组件自身没有对应的删除方法,需要用父类执行 Object.Destroy() 方法才能删除它。

  • GameObect.AddComponent<组件名>():添加组件
  • Destroy(GameObect.GetComponent<组件名>()):删除组件

示例1:动态添加与删除脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    GameObject obj;
	void Start () {
        obj = GameObject.Find("Cube");
	}
    void OnGUI()
    {
        if(GUILayout.Button("添加脚本",GUILayout.Height(50),GUILayout.Width(100)))
        {
            obj.AddComponent<test>();
        }
        if(GUILayout.Button("删除脚本",GUILayout.Height(50),GUILayout.Width(100)))
        {
            Destroy(obj.GetComponent<test>());
        }
    }
}

 测试用来添加的脚本代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour {

	void Start () {
        Debug.Log("脚本开始运行!");
		
	}
	void OnDestroy()
    {
        Debug.Log("脚本被销毁!");
    }
}

 

实例2:创建一个立方体对象(Cube),然后为其添加渲染组件,再创建个“Test”脚本组件(只需在Start方法中写一行Debug.Log("内容随意");即可)用来测试脚本组件是否添加成功。

将准备好的贴图赋值给texture变量,其余游戏对象无关紧要。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class E3_04 : MonoBehaviour {
    private GameObject obj; //创建游戏对象
    private Renderer render;    //渲染器
    public Texture texture;    //贴图
	void Start () {
        obj = GameObject.Find("Cube");  //获取游戏对象
        obj.AddComponent<Test>();   //给当前对象添加一个脚本组件
        render = obj.GetComponent<Renderer>();  //获取该对象的渲染器
	}
	
    void OnGUI()
    {
        if(GUILayout.Button("添加颜色",GUILayout.Height(70),GUILayout.Width(120)))
        {
            //修改渲染器的颜色
            render.material.color = Color.green;
            //为了避免残留,将贴图置空
            render.material.mainTexture = null;
        }
        if (GUILayout.Button("添加贴图", GUILayout.Height(70), GUILayout.Width(120)))
        {
            //为了避免残留,将贴图置空
            render.material = null;
            //添加组件贴图
            render.material.mainTexture = texture;
        }
    }
	void Update () {
		
	}
}

运行结果:点击“添加颜色”立方体会变为绿色,点击添加贴图,立方体表面会添加上贴图,下面一行为“Test”脚本打印的文字。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

healthLau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值