【愚公系列】2022年02月 U3D全栈班 014-GameObject相关函数

举报
愚公搬代码 发表于 2022/02/20 02:12:06 2022/02/20
948 0 0
【摘要】 一、GameObject相关函数函数说明GameObject()构造函数,创建GameObjectSetActive()Activates/Deactivates 启用/停用 GameObjectDestory()销毁GameObject启用/停用GameObjectInstantiate()克隆函数,克隆一个Object到当前场景中GetComponent<T>()通过GameObjec...

一、GameObject相关函数

函数 说明
GameObject() 构造函数,创建GameObject
SetActive() Activates/Deactivates 启用/停用 GameObject
Destory() 销毁GameObject启用/停用GameObject
Instantiate() 克隆函数,克隆一个Object到当前场景中
GetComponent<T>() 通过GameObject实例获取组件
AddComponent<T>() 给GameObject实例添加组件
SendMessage() 调用GameObject的methodName方法
SendMessageUpwards() 调用GameObject以及所有父物体的methodName方法
BroadcastMessage() 调用GameObject以及所有子物体身上的methodName方法

注意:SendMessage方法,必须是GameObject身上挂载的脚本有methodName方法

具体使用方式:
1.定义两个对象
在这里插入图片描述

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

public class Ryunm_ScriptsInUnity : MonoBehaviour
{
    public GameObject qiaofeng;
    public GameObject zhangwuji;

    // Start is called before the first frame update
    void Start()
    {
    	//创建
        GameObject newObj = new GameObject("xxx");
        //启用
        newObj.SetActive(true);
		//克隆
        GameObject cloneObj = Instantiate(newObj);
        //添加组件
        cloneObj.AddComponent<SpriteRenderer>();
        //获取组件
        var sr = cloneObj.GetComponent<SpriteRenderer>();
        sr.sprite = firstSprite;
		//销毁组件
        Destroy(newObj,2);

    }

    // Update is called once per frame
    //每帧都会执行一次
    void Update()
    {
    	//SendMessage执行游戏对象上的方法
        if (Input.GetKeyDown(KeyCode.Q))
        {
            qiaofeng.SendMessage("GongFu_02");
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            qiaofeng.SendMessage("GongFu_01");
        }
        if (Input.GetKeyDown(KeyCode.E))
        {
            zhangwuji.SendMessage("GongFu_03");
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            zhangwuji.SendMessage("GongFu_04");
        }

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

public class Ryunm_SendMessage : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void GongFu_01()
    {
        print("独孤九剑");
    }
    public void GongFu_02()
    {
        print("降龙十八掌");
    }
    public void GongFu_03()
    {
        print("九阳真经");
    }
    public void GongFu_04()
    {
        print("六脉神剑");
    }
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。