C#初级编程

1. 作为行为组件的脚本

using UnityEngine;
using System.Collections;

public class ExampleBehaviourScript : MonoBehaviour 
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            GetComponent<Renderer>().material.color = Color.red;
        }
        if (Input.GetKeyDown(KeyCode.G))
        {
            GetComponent<Renderer>().material.color = Color.green;
        }
        if (Input.GetKeyDown(KeyCode.B))
        {
            GetComponent<Renderer>().material.color = Color.blue;
        }
    }
}

Q1:什么是MonoBehaviour?MonoBehaviour

2. 变量和函数

using UnityEngine;
using System.Collections;

public class VariablesAndFunctions : MonoBehaviour
{   
    int myInt = 5;
    
    
    void Start ()
    {
        myInt = MultiplyByTwo(myInt);
        Debug.Log (myInt);
    }
    
    
    int MultiplyByTwo (int number)
    {
        int ret;
        ret = number * 2;
        return ret;
    }
}

3. 约定和语法

4. IF 语句

5. 循环

6. 作用域和访问修饰符

7. Awake 和 Start

using UnityEngine;
using System.Collections;

public class AwakeAndStart : MonoBehaviour
{
    void Awake ()
    {
        Debug.Log("Awake called.");
    }
    
    
    void Start ()
    {
        Debug.Log("Start called.");
    }
}

Q1. 使用Awake而不是使用构造函数初始化,因为组件的序列化状态在构造时是未定义的。Awake和构造函数一样只被调用一次 Awake

8. Update 和 FixedUpdate

using UnityEngine;
using System.Collections;

public class UpdateAndFixedUpdate : MonoBehaviour
{
    void FixedUpdate ()
    {
        Debug.Log("FixedUpdate time :" + Time.deltaTime);
    }
    
    
    void Update ()
    {
        Debug.Log("Update time :" + Time.deltaTime);
    }
}

Q1. Update 作用于每一帧变化时
Q2. FixedUpdate 每隔一个固定时间段起用
Q3. StackOverFlow update Vs fixedupdate

posted @ 2023-04-26 13:24  冯大善人  阅读(30)  评论(0)    收藏  举报