1.之前在跟视频学习做一个游戏的开始界面UI时,因为视频里用的NGUI,它自带Tween可以直接实现UI界面之间的动画切换;而我用的UGUI,因为是原生的,效果还行也懒得安装插件了,机缘巧合下载安装了DOTween,学习后发现DOTween很强大很好用;
比如在切换界面时,可以用transform.DOScale,transform.DoMove等;
我为了方便,类似NGUI上面的Tween这种,用DOTween写了两个脚本
(1).DOScale.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class DoScale : MonoBehaviour {
public Vector3 From = new Vector3 (0, 0, 0);
public Vector3 To = new Vector3 (0, 0, 0);
public float Duration = 0.3f;//持续时间
public void DoScaleTo(){
transform.localScale = From;
transform.DOScale (To, Duration);
}
public void DoScaleBack(){
transform.localScale = To;
transform.DOScale (From,Duration);
}
}
(2).DOMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class DoMove : MonoBehaviour {
public Vector3 From = new Vector3 (0, 0, 0);
public Vector3 To = new Vector3 (0, 0, 0);
public float duration= 0.3f;
public bool Yoyo = false; //来回移动(a——>b,b——>a)
public bool Restart = false; //重复上一次移动(a——>b,a——>b)
public bool Incremental = false; //第一次移动后,继续向移动方法移动(a——>b,b——>c,.....)
void Start(){
//-1表示次数为无限
if (Yoyo) {
transform.localPosition = From;
transform.DOLocalMove (To, duration).SetLoops (-1, LoopType.Yoyo);
}
if (Restart) {
transform.localPosition = From;
transform.DOLocalMove (To, duration).SetLoops (-1, LoopType.Restart);
}
if (Incremental) {
transform.localPosition = From;
transform.DOLocalMove (To, duration).SetLoops (-1, LoopType.Incremental);
}
}
public void DoMoveTo(){
transform.localPosition = From;
transform.DOLocalMove (To, duration);
}
public void DoMoveBack(){
transform.localPosition = To;
transform.DOLocalMove (From,duration);
}
}
这样把需要进行切换动画的UI界面添上脚本,再使用UI界面的button的OnClick()调用方法就可以了
2.还遇到一个问题,教程里面点击角色左右拖拽时,让角色跟着左右旋转; 使用的是NGUI的SpinWithMouse脚本,我用UGUI做的,只能自己写了,查了相关资料,模仿写了个
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinWithMouse : MonoBehaviour{
public Transform target;
public float speed = 3.5f;
private float AxisX;
void Start(){
if (target == null)
target = this.transform;
}
void OnMouseDrag(){
AxisX = -Input.GetAxis ("Mouse X"); //”-”是因为角色和我们点击鼠标拖拽时是面对面的,方向相反
}
void OnMouseUp(){
AxisX = 0f; //归零
}
void Update(){
target.Rotate (new Vector3 (0, AxisX, 0) * speed);
}
}
注意:1.给你要点击鼠标拖拽旋转的那个物体添加Collider,2.给该物体添加此脚本(SpinWithMouse)
3.替换图片时也遇到点情况,NGUI中利用图集,直接sprite.name=xxx(图片名字)就可以切换图片了,UGUI怎么切换呢,看网上大佬给出三种,我觉得Resource.Load()这种最简单
把需要切换的图片UI都复制一份放到Resource文件夹下,可以自己在Resource下再新建一个文件夹方便区分,比如头像图片我建了个UI_Avatar,道具图片放到了UI_Property里面,这样就可以模仿NGUI那样切换了,例如头像
private Image playerAvatar;
...
...
playerAvatar.sprite = Resources.Load(“UI_Property/”+xxx,typeof(Sprite))as Sprite //xxx为图片名字
来源:CSDN
作者:<somewhere>
链接:https://blog.csdn.net/qq_39745907/article/details/104010566