Transform设置父物体,查找子物体+Input类
设置父物体
在代码中更深入理解GameObject和Transform
public GameObject target;
public Transform target_transform;
transform.parent=target.transform;
transform.parent=target_transform;
transform.SetParent(target.transform);
transform.SetParent(target_transform);
因为GameObject肯定有Transform组件 ,所以这样做target.transform;
因为Transform不能独立存在,所以必然存活于游戏物体,所以可以这样做target_transform.gameObject;
transform查找子物体API
transform.childCount:子物体的数量。
transform.GetChild(i);根据index来查找子物体,特性:子物体的子物体是不会管的。
Transform t=transform.find("Cube(2)"); 根据游戏物体的名字进行精确查找,也不会搜索子物体的子物体
GameObject查找游戏物体
GameObject go=GameObject.Find("GameObject");能根据游戏物体名字在所有场景内游戏物体中查找,好用但是效率很低,谨慎使用;
通过Tag来进行查找游戏物体
//当有多个tag是NPC的时候,查找到的是最后创建的tag是NPC的游戏物体
//查找游戏物体tag是NPC
//GameObject go=GameObject.FindGameObjectWithTag("NPC");
//if(go)
// Debug.Log("go:"+go.name);
//当游戏场景中有多个游戏物体tag是NPC,同时查找到,并返回一个游戏物体数组
GameObject[] gos = GameObject.FindGameObjectsWithTag("NPC");
for(int i = 0; i < gos.Length; i++)
{
Debug.Log("name:" + gos[i].name);
}
Input类
//当A键按下瞬间执行一次
if(Input.GetKeyDown(KeyCode.A)){
Debug.Log("A");
}
//当B键按下时执行,执行次数大于1
if(Input.GetKey(KeyCode.B)){
Debug.Log("B");
}
//C键被按下抬起瞬间执行一次
if(Input.GetKeyUp(KeyCode.C)){
Debug.Log("C");
}
if(Input.GetMouseButton(1)){
Debug.Log(1);
}
if(Input.GetMouseButton(2)){
Debug.Log(2);
}
if(Input.GetMouseButton(0)){
Debug.Log(0);
}
//按下A键 从0到-1 会有很多随机的小数,渐变到-1
//float h=Input.GetAxis("Horizontal");
//float v=Input.GetAxis("Vertical");
//Debug.Log("h:"+h+"V:"+v);
//值在-1 0 1 三个值之间切换,不会有中间值进行渐变
//float h1=Input.GetAxisRaw("Horizontal");
//float v1=Input.GetAxisRaw("Vertical");
//Debug.Log("h1:"+h1+",V1:"+v1);
//检测鼠标左键
if(Input.GetMouseDown("Fire1")){
Debug.Log("Fire1");
实例:坦克的运动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TankController : MonoBehaviour
{
public float speed=0.5f;
private float h, v;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
transform.Rotate(0, h, 0);
transform.Translate(Vector3.forward * v * speed,Space.Self);
}
}
运行结果:
该系列专栏为网课课程笔记,仅用于学习参考。
原文地址:https://blog.csdn.net/m0_74236534/article/details/142706851
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!