9. Aquisição de objetos Unity, uso de recursos, temporização e operações vetoriais

1. Obtenha o objeto objeto no script

O primeiro método: use a função Localizar (não recomendado)
Este método não é conveniente e o nome do modelo pode ser alterado no editor, que está sujeito a erros.

    void Start()
    {
    
    
        GameObject node = GameObject.Find("正方体");//查找获取编辑器中名称为“正方体”的模型
    }

A segunda maneira: usar atribuição de atributo (recomendado)
Este método é semelhante a referências de componentes, configurando um atributo no arquivo de script e, em seguida, atribuindo este atributo no editor, a vantagem disso é que não importa o modelo Como alterar o nome ou local, o editor se adaptará automaticamente a essa mudança e não é fácil cometer erros.

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

public class BallScript : MonoBehaviour
{
    
    
    public GameObject node; //在此处设置一个属性

    // Start is called before the first frame update
    void Start()
    {
    
    
        //赋值后就可以对物体传输过来的物体进行一些想要的操作
    }

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

Em seguida, atribua valores às propriedades definidas no script no editor
insira a descrição da imagem aqui

2. Aquisição de objetos pai/filho

Na unidade, o filho no nível pai é mantido pela classe Transform para
obter o pai:

Transform parent = this.transfrom.parent;

Obtenha o nó pai:

GameObject parentNode = this.transform.parent.gameobject;

Obter filhos:

//第一种:遍历查找
foreach(Transform child in transform)
{
    
    
    Debug.Log("* 子物体:" + child.name);
}
//第二种:索引查找
Transform child2 = this.transform.GetChild(0);
Debug.Log("* 子物体:" + child2.name);
//第三种:名称查找
Transform child3 = this.transform.Find("正方体");
Debug.Log("* 子物体:" + child3.name);

3. Manipulação de objetos

3.1 Defina o nó pai

this.transform.SetParent(node);//node为某一个节点模型
this.transform .SetParent(null);//null表示设置为一级节点

3.2 Ocultar/Mostrar Objetos

Transform child = this.transform.Find("/aa");//前面的 / 表示在根节点开始查找
if (child.gameObject.activeSelf)//如果当前物体显示(activeself用于判断当前物体是否是激活状态)
 {
    
    
     child.gameObject.SetActive(false);//隐藏物体
 }
 else
 {
    
    
     child.gameObject.SetActive(true);//显示物体
 }

4. Uso de recursos

No script, você também pode se referir a um recurso
como:
AudioClip arquivo de áudio
Textura mapa de textura
Material material
...
Exemplo: controle de script arquivo de áudio audioclip primeiro monta um componente AudioSource
em um objeto no editor de interface , sem necessidade de configurá-lo na interface neste momento Defina sua propriedade AudioClip , que é definida em seu script montado, conforme mostrado na figura: (Geralmente, depois de adicionar um componente no editor de interface, você pode arrastar e soltar diretamente o arquivo de recurso na propriedade correspondente , mas agora você precisa fazer o script) e depois montar um script no modelo da bola , o código é o seguinte:
insira a descrição da imagem aqui

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

public class BallScript : MonoBehaviour
{
    
    
    public AudioClip audioclipSucess; //定义一个属性,用于接收界面编辑器设置的'成功提示音'

    public AudioClip audioclipFail;//定义一个属性,用于接收界面编辑器设置的'失败提示音'

    private AudioSource audio;

    // Start is called before the first frame update
    void Start()
    {
    
    
        audio = this.GetComponent<AudioSource>();//获取当前模型下的audiosource组件
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if(Input.GetKeyDown(KeyCode.A))
        {
    
    
            audio.PlayOneShot(audioclipSucess);//播放一次
        }
        if(Input.GetKeyDown(KeyCode.D))
        {
    
    
            audio.PlayOneShot(audioclipFail);//播放一次
        }
    }
}

Depois de carregar o código, você precisa especificar as duas propriedades acima no editor de interface, conforme mostrado na figura abaixo, e executar o programa após especificar.
insira a descrição da imagem aqui

5. Matriz de recursos

Ao definir atributos, se você precisar de uma variável para armazenar vários conteúdos, considere usar uma matriz para implementá-la e definir uma variável de matriz no script:

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

public class KaTongLogic : MonoBehaviour
{
    
    

    public AudioClip[] audioClips;//添加一个数组类型的变量

    // Start is called before the first frame update
    void Start()
    {
    
    

    }

    // Update is called once per frame
    void Update()
    {
    
    
        if(Input.GetMouseButtonDown(0))
        {
    
    
        	NextAudio();
        }
    }
	private void NextAudio()
	{
    
    
		//随机播放
		int index = Random.Range(0,audioClips.Length);
		AudioClip audio = this.audioClips[index];
		AudioSource audioSource = this.GetComponent<AudioSource>();
		audioSource.clip = audio;	//给组件属性赋值
		audioSource.Play();	//开始播放
	}
}

Ao atribuir valores às propriedades do array na interface, você pode atribuir valores várias vezes:
insira a descrição da imagem aqui

6. Marcação de chamadas

Chame Invoke regularmente, que geralmente é chamado de timer, herdado de MonoBehavior , e as funções comumente usadas são as seguintes:
Invoke(
func, delay): chame apenas uma vez O intervalo de chamada é executado de acordo com o intervalo
IsInvoking(func): determine se está sendo agendado
CancelInvoke(func): cancela a chamada e a remove da fila de despacho

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

public class KaTongLogic : MonoBehaviour
{
    
    

    public AudioClip[] audioClips;

    // Start is called before the first frame update
    void Start()
    {
    
    
        Debug.Log("* Start。。。。" + Time.time);

        //注意函数名要以字符串的形式给出
        this.Invoke("DoSomething",1);// 1 秒后调用这个函数

        this.InvokeRepeating("DoSomething",2,4);第一次是2秒后调用这个函数,后面就是按照间隔4秒循环调用
    }

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

    }

    public void DoSometing()
    {
    
    
        Debug.Log("* DoSomethis。。。。" + Time.time);
    }
}

7. Problema de encadeamento da unidade? ?

Não há multithreading na unidade , então não há necessidade de considerar simultaneidade, multithreading ou algo assim. . .
Você pode usar o ID do encadeamento para verificar
usando System.Threading;
Thread.CurrentThread.ManagedThreadId;
imprimir o ID do encadeamento na função start(), função update() e função de temporização, respectivamente, e descobrir que o número do ID é o mesmo

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

using System.Threading;

public class KaTongLogic : MonoBehaviour
{
    
    

    public AudioClip[] audioClips;

    // Start is called before the first frame update
    void Start()
    {
    
    
        Debug.Log("* Start。。。。" + Time.time);

        Debug.Log("* Start...." + Thread.CurrentThread.ManagedThreadId);//输出当前函数所在线程ID

        //注意函数名要以字符串的形式给出
        this.Invoke("DoSomething",1);// 1 秒后调用这个函数

        this.InvokeRepeating("DoSomething",2,4);//第一次是2秒后调用这个函数,后面就是按照间隔4秒循环调用
    }

    // Update is called once per frame
    void Update()
    {
    
    
        Debug.Log("* Update...." + Thread.CurrentThread.ManagedThreadId);//输出当前函数所在线程ID
    }
	
	//延迟调用函数
    public void DoSometing()
    {
    
    
        Debug.Log("* DoSometing...." + Thread.CurrentThread.ManagedThreadId);//输出当前函数所在线程ID
        Debug.Log("* DoSomethis。。。。" + Time.time);
    }
}

8. Caso: usando um temporizador para obter uma mudança gradual na velocidade

O código para realizar a rotação de aceleração lenta e rotação de parada lenta do modelo
:

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


public class KaTongLogic : MonoBehaviour
{
    
    
    public float maxSpeed = 1000;

    float m_speed = 0;//当前速度
    bool m_speedUp = false;//是否加速
    // Start is called before the first frame update
    void Start()
    {
    
    
        this.InvokeRepeating("AdjustSpeed", 0.1f,0.1f);//循环调用
    }

    // Update is called once per frame
    void Update()
    {
    
    
        //点一下加速,再点减速,交替执行
        if(Input.GetMouseButtonDown(0))
        {
    
    
            m_speedUp = !m_speedUp;
        }
        if (m_speed > 0)
        {
    
    
            this.transform.Rotate(0, 0, m_speed * Time.deltaTime, Space.Self);
        }

    }

    public void AdjustSpeed()
    {
    
    
        if (m_speedUp)
        {
    
    
            //阈值判断
            if(m_speed < maxSpeed)
            {
    
    
                m_speed += 20;
            }
        }
        else
        {
    
    
            m_speed -= 20;
            //阈值判断
            if(m_speed < 0)
            {
    
    
                m_speed = 0;
            }
        }
    }
}

efeito real:

O temporizador Unity realiza o gradiente de velocidade

10. Vetor em unidade

Vetor: Existe uma direção e um comprimento.Na unidade, o vetor tridimensional Vector3 é mais usado .

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

public class KaTongLogic : MonoBehaviour
{
    
    
    // Start is called before the first frame update
    void Start()
    {
    
    
        //两个API
        Vector3 v1 = new Vector3 (6, 8, 0);

        float len = v1.magnitude; //求向量的长度
        Debug.Log("v1的长度:" + len);

        Vector3 v2 = v1.normalized;//向量的标准化
        Debug.Log("v1的标准化:" + v2);

        //几个常量
        Vector3 vZero = Vector3.zero;//即(0,0,0)
        Vector3 vUp = Vector3.up;//即(0,1,0)
        Vector3 vRight = Vector3.right;//即(1,0,0)
        Vector3 vForward = Vector3.forward;//即(0,0,1)

        Vector3 a = new Vector3(3, 4, 0);
        Vector3 b = new Vector3(5, 6, 0);

        //向量加法
        Vector3 c = a + b;

        //向量减法
        Vector3 d = a - b;

        //向量乘法
        Vector3 e = a * 2;//标量乘法
        float f = Vector3.Dot(a,b);//点积
        Vector3 g = Vector3.Cross(a, b);//差积

        //向量赋值
        Vector3 h = a;//注意不能赋值为null
    }

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

    }
}

10.1 Variação do Vetor

Ele pode ser usado para calcular a distância entre dois objetos, para ser preciso, para calcular a distância entre os pontos de pivô de dois objetos. Antes de medir a distância, você deve verificar se o ponto de pivô entre os dois objetos está no mesmo plano, caso contrário, podem existir erros .

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

public class KaTongLogic : MonoBehaviour
{
    
    
    public GameObject target;
    // Start is called before the first frame update
    void Start()
    {
    
    
        Vector3 p1 = this.transform.position;//当前物体的坐标(相对于原点)
        Vector3 p2 = target.transform.position;//目标物体的坐标(相对于原点)
        
        Vector3 direction = p2 - p1;//计算两者间的方向向量
        float distance = direction.magnitude;//计算距离

        //使用API进行计算
        float distance2 = Vector3.Distance(p2, p1);

        Debug.Log("* 两者之间的距离:" + distance );
        Debug.Log("* 两者之间的距离:" + distance2);
    }

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

    }
}

Memória auxiliar:
insira a descrição da imagem aqui

10.2 Aplicações de vetores

Por exemplo, para definir a velocidade de movimento de um objeto em um script, você pode definir um valor do tipo float separadamente e, em seguida, usar a função translate() para especificar em qual direção o objeto se move, mas isso não é universal e pode é impossível alterar a direção do movimento arbitrariamente, você pode usar especificado como um vetor.
Exemplo:

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


public class KaTongLogic : MonoBehaviour
{
    
    
    public Vector3 speed; //定义一个三维向量来控制物体移动(包括方向和速度)

    // Start is called before the first frame update
    void Start()
    {
    
    
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        Vector3 delta = speed * Time.deltaTime;

        this.transform.Translate(delta, Space.Self);
    }
}

Desta forma, a direção e a velocidade do movimento do objeto podem ser especificadas arbitrariamente no editor de interface. Insira valores nas caixas de entrada x, y e z na figura abaixo, que podem ser especificadas arbitrariamente:
insira a descrição da imagem aqui

Atualizando continuamente, por favor, preste mais atenção para ...

Acho que você gosta

Origin blog.csdn.net/FY_13781298928/article/details/129968633
Recomendado
Clasificación