脚本的基本使用

定义与挂载monobehaviour

1.新建一个场景

Unity基础-脚本的基本使用 随笔 第1张

2.新建脚本

Unity基础-脚本的基本使用 随笔 第2张

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyCoponent : MonoBehaviour {

    // Use this for initialization
        // 第一帧调用所需执行的函数
    void Start () {
        
    }
    
    // Update is called once per frame
        // 每一帧所需要执行的函数
    void Update () {
        
    }
}

3.新建挂载脚本

Unity基础-脚本的基本使用 随笔 第3张

在脚本中动态挂载脚本

 gameObject.AddComponent<new2>();   // 在脚本中动态挂载脚本

代码如下:

    // Use this for initialization
    void Start () {
        gameObject.AddComponent<new2>();    // 在脚本中动态挂载脚本
    }

寻找删除禁用

寻找:

Renderer render = gameObject.GetComponent<Renderer>();  // 寻找到脚本
gameObject.GetComponentInChildren<Renderer>();  // 子节点第一个
gameObject.GetComponentInParent<Renderer>();    // 父节点第一个

删除:

Destroy(render);    // 删除脚本

禁用设置:

render.enabled = true;  //  脚本设置是否可用
render.enabled = false; 

脚本的生命周期函数

// 初始化操作,一般根据Unity规则,不使用构造函数而使用初始化的函数
private void Awake(){}
// Use this for initialization
void Start () {}
// Update is called once per frame
void Update () {}
// 被删除调用
private void OnDestroy() {}
// 被启用时调用
private void OnEnable() {}
// 被禁用时调用
private void OnDisable() {}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄