U3D:各种小功能合集

目录

移动物体到点击位置

添加空间锚点

隐藏/显示物体

判断物体是否在场景中显示

点击UI控件时不触发场景其它点击响应

射线检测,获取鼠标坐标值

获取当前物体的子物体 

通过标签查找物体 

物体移动、缩放和旋转 

物体围绕轴或者其它物体旋转

 读取文本位置

变换颜色 

计算两物体的距离

加载预制体

某物体设为子物体 

 跟随相机

动态添加脚本 

unity中三种调用其他脚本函数的方法 

OnGUI

 加载图片并显示

加载视频

场景切换

控制物体闪烁

控制动画播放和停止


 

移动物体到点击位置

点击鼠标(也可以设置触发其它),物体移动到鼠标点击位置。

  • Camera 在正交模式下:
public Gameobject cube;
public Vector3 tempPos;
void Update()
    {
       if (Input.GetMouseButtonDown(0))
       {
           tempPos = Input.mousePosition;
           tempPos = Camera.main.ScreenToWorldPoint(tempPos);
           tempPos.z = 0;
           cube.transform.position = tempPos;
        }
}
  • Camera 在透视模式下
public Gameobject cube;
public Vector3 tempPos;
void Update()
    {
       if (Input.GetMouseButtonDown(0))
       {
           tempPos = Input.mousePosition;
           tempPos = Camera.main.ScreenToWorldPoint(tempPos);
           tempPos.z = 10;
           cube.transform.position = tempPos;
        }
}
//须给定深度值z,不然物体一直在视野最前面

添加空间锚点

World Anchor空间锚点提供了一种能够将物体保留在特定位置和旋转状态上的方法。

先移动物体到指定位置,再添加锚点固定。

  • 命名空间
UnityEngine.VR.WSA
  • 添加空间锚点
WorldAnchor anchor = gameObject.AddComponent<WorldAnchor>();
  • 移除空间锚点

Destroy(gameObject.GetComponent<WorldAnchor>());
//不再将GameObject固定在特定位置,同时在场景中也不再移动它
DestroyImmediate(gameObject.GetComponent<WorldAnchor>());
//立刻在场景中移动对象

隐藏/显示物体

  • 鼠标直接点击屏幕任何地方
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CallParts : MonoBehaviour
{
    public MeshRenderer rander;//监视被挂载物体的网格渲染器
    private void Update()//点击鼠标左键,隐藏/显示物体
    {
        if (Input.GetMouseButtonDown(0))
        {
            rander.enabled = !rander.enabled;
        }
    }
}
//脚本可以挂载在如何地方,然后在“rander”上挂载需要隐藏/显示的物体。 
//或者定义好物体之后,直接一行代码实现
cube.gameObject.GetComponent<Renderer>().enabled = false;

 

  • 通过点击按钮Button实现 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CallParts : MonoBehaviour
{
    public GameObject button;//按钮
    public GameObject objCube;//物体
    //隐藏物体必须写在Start函数里,因为Awake函数最先执行,然后执行Start函数,再执行Update函数
    void Start()
    {
        GameObject ObjCube = GameObject.Find("Cube");//查找Cube
        ObjCube.SetActive(false);//开始时先不显示
    }

    public void OnButton1Click()//点击事件:点击按钮换显示/隐藏零件
    {
        ObjCube.SetActive(!ObjCube.activeSelf);//显示/隐藏零件cube
    }
//将脚本挂载在按钮上,添加按钮的Click事件,对象为cube。
//当物体为子按钮时,可以实现弹出二级按钮的功能。

判断物体是否在场景中显示

public GameObject obj;
if(obj.activeInHierarchy)
{
Debug.Log("物体obj在场景中显示");
}
//可以实现在物体显示的情况下执行操作,物体不显示则不执行操作

点击UI控件时不触发场景其它点击响应

using UnityEngine.EventSystem
//所属命名空间
if (Input.GetMouseButtonDown (0)) 
{
    if (EventSystem.current.IsPointerOverGameObject ())
    {
	Debug.Log ("点击到的是UI");
    }
    else 
    { 
    //执行场景内其它点击事件
    }
}

射线检测,获取鼠标坐标值

using UnityEngine;
using System.Collections;

public class cs : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButton(0))//点击鼠标,若有物体,则出现射线
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线
            RaycastHit hitInfo;//声明一个变量来引用输出信息
            if (Physics.Raycast(ray, out hitInfo))//Physics.Raycast为bool函数,碰撞到为真
            {
                Debug.DrawLine(ray.origin, hitInfo.point,Color.red);//划出射线,只有在scene视图中才能看到
                GameObject gameObj = hitInfo.collider.gameObject;//碰撞到的物体
                Debug.Log("click object name is " + gameObj.name);
                if (null != hitInfo.transform)
                {
                    Debug.Log(hitInfo.point);//点击鼠标的坐标信息
                }
            }
        }
    }
}
//脚本挂载在摄像机上
//注意物体是否添加Box Collider组件

获取当前物体的子物体 

void Start () 
{
        Transform[] father = GetComponentsInChildren<Transform>();
        foreach (var child in father)
        {
            Debug.Log(child.name);
        }
}
//拖到父物体上即可
//获取父物体下的所有子物体,包含孙物体...
public Transform father;
void Start()
{       
    for (int i = 0; i < father.childCount; i++)
    {
    var child = father.GetChild(i).gameObject;
    Debug.Log(child.name);
    }
}
//获取父物体下的子物体,不获取孙物体...

通过标签查找物体 

public Transform father;
void Start()
{
        GameObject[] objTagName = GameObject.FindGameObjectsWithTag("标签");//查找出的物体要保存到数组里
        foreach(var son in objTagName)
        {
            Debug.Log(son.name);
        }
}
//事先要给物体添加Tag

物体移动、缩放和旋转 

//移动物体
cube.transform.Translate (new Vector3(-0.5f, 0f, 0f));//负左正右
//缩放物体
cube.transform.localScale *= 1.2f;
//旋转物体
cube.transform.Rotate (new Vector3(0, 10, 0));
//围绕某物体旋转
cube.transform.RotateAround (cylinder.transform.position, Vector3.up, 10);

物体围绕轴或者其它物体旋转

transform.RotateAround(new Vector3 (10f,0f, 0f), new Vector3 (0f, 0f, 1f), 3f); 
//(围绕点,围绕轴,旋转角度)

 

    public Transform AxThing;//定义为轴的物体

    void Update()
    {
        this.transform.RotateAround(AxThing.position, AxThing.up, 20 * Time.deltaTime);
        //(位置,物体轴向,角度)
    }

 读取文本位置

//将文本文件放在Assets下的StreamingAssets文件夹中(没有手动创建)

string ContentData1 = Application.streamingAssetsPath + "\\" + "data1.txt";//读取文本位置
string PathData1 = ContentData1.Replace(@"/", @"\");//转换符号,使满足读取要求

变换颜色 

//物体要有MeshRenderer组件

public GameObject jjj;

jjj.GetComponent<MeshRenderer>().material.color = Color.blue;//变换颜色

jjj.GetComponent<MeshRenderer>().material.color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));//随机颜色

计算两物体的距离

//定义两物体后,直接一行代码实现
float distance = Vector3.Distance(cube1.transform.position, cube2.transform.position);

加载预制体

public GameObject palyerNet;

void Start()
  {
      GameObject prefabInstance = Instantiate(palyerNet);//初始化预制体
  }

某物体设为子物体 

hhhhhh.transform.parent = this.transform;
//脚本挂在父物体(this)上,hhhhhh为子物体

 跟随相机

using UnityEngine;
using System.Collections;

public class CameraFlow : MonoBehaviour
{
    public Transform target;
    private Vector3 offset;
    // Use this for initialization
    void Start()
    {
        offset = target.position - this.transform.position;

    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position = target.position - offset;
    }
}

 unity 常用的几种相机跟随

动态添加脚本 

//按下F2键,动态加载hhh脚本(注意此脚本放在scripts文件夹下)。该脚本挂在该物体上   
if (Input.GetKeyDown(KeyCode.F2))
   {
       this.gameObject.AddComponent<hhh>();
   }

unity中三种调用其他脚本函数的方法 

第一种,被调用脚本函数为static类型,调用时直接用  脚本名.函数名()。很不实用……

第二种,GameObject.Find("脚本所在物体名").SendMessage("函数名");  此种方法可以调用public和private类型函数

第三种,GameObject.Find("脚本所在物体名").GetComponent<脚本名>().函数名();此种方法只可以调用public类型函数

OnGUI

//第一种格式
GUI.xxx()    ---GUI.Label(new Rect(100, 100, 500, 50), "Hello,this world!");
//第二种格式
GUILayout.xxx()    ---GUILayout.Label("请输入你的名字:");  //默认处于左上角

 加载图片并显示

//图片放在Assets/Resources文件夹下


//法一:加载的图片为sprite类型
using UnityEngine.UI;

object obj = Resources.Load("图片名字", typeof(Sprite));//读取图片
Sprite sp = obj as Sprite;
img.sprite = sp;//显示再UI控件Image上


//法二:加载的图片为默认Texture类型,需要先转换为sprite类型
Texture2D img111 = Resources.Load("DLAM") as Texture2D;
Sprite pic = Sprite.Create(img111, new Rect(0, 0, img111.width, img111.height), new Vector2(0.5f, 0.5f));//后面Vector2就是UI的Image控件Anchors的Pivot的x/y属性值
img.sprite = pic;

加载视频

Unity加载资源文件夹中的图片和视频并显示_航空界的小爬虫-CSDN博客

unity用自带的Video player播放视频_航空界的小爬虫-CSDN博客

场景切换

  1. 在File->Building Setting中设置添加需要转换的场景。
  2. 脚本中添加Application.LoadLevel()函数,括号中加入场景的名称或编号即可,例如: if(GUI.Button(Rect(0,0,50, 50) ,"切换场景")){ Application.LoadLevel("scene1") ; }
  3. 需要注意的是切换场景后所有加载物体都将删除,除非使用Object.DontDestroyOnLoad(Object)添加标记,例如人物角色在切换场景后需要保留,就可以用此方法。
  4. 注意,每个场景对应的Start都是在当前场景启用后才执

控制物体闪烁

public class BlinkColor : MonoBehaviour
{
    //创建一个常量,用来接收时间的变化值
    private float shake;
    //通过控制物体的MeshRenderer组件的开关来实现物体闪烁的效果
    private MeshRenderer Obj1;
    // Use this for initialization
    void Start()
    {
        Obj1 = gameObject.GetComponent<MeshRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        shake += Time.deltaTime;
        //Debug.Log(shake);
        //取余运算,结果是0到被除数之间的值
        //如果除数是1 1.1 1.2 1.3 1.4 1.5 1.6 
        //那么余数是0 0.1 0.2 0.3 0.4 0.5 0.6
        if (shake % 1 > 0.5f)
        {
            Obj1.enabled = true;
        }
        else
        {
            Obj1.enabled = false;
        }
    }
}

控制动画播放和停止

public class StartStop : MonoBehaviour
{
    private Animation hhh;
    public Button jjj;

    void Start()
    {
        hhh = this.GetComponent<Animation>();//获取物体动画
        jjj.onClick.AddListener(hhhMain);
    }

    public void hhhMain()
    {
        hhh.Stop("Blink");//“”里面填动画的名字
    }
}

 

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值