unity ugui怎么判断停留在ugui上

Unity进阶技巧 - 动态创建UGUI - 简书
下载简书移动应用
写了35830字,被390人关注,获得了604个喜欢
Unity进阶技巧 - 动态创建UGUI
项目中有功能需要在代码中动态创建UGUI对象,但是在网上搜索了很久都没有找到类似的教程,最后终于在官方文档中找到了方法,趁着记忆犹新,写下动态创建UGUI的方法,供需要的朋友参考
你将学到什么?
如何设置UI的缩放模式和尺寸
如何添加UI动画效果
如何使用Button的基本响应事件
如何动态创建UGUI对象
一、新建一个Test项目
首先我们新建一个名为Test的项目来实践我们这次的内容,项目创建成功后,我们新建一个Button对象,如下图:
新建Button对象
新的UGUI全部都基于一个Canvas画布,如果你的场景里面没有Canvas,当你创建一个UI对象时,编辑器会自动帮你创建一个Canvas
编辑器自动创建的Canvas
然后我们设置一下Cavans的缩放模式和尺寸,本例中我们以iPhone6的尺寸大小为准,我们选中Canvas,然后在其Canvas Scaler组件中,修改Ui Scale Mode为Scale With Screen Size,然后将分辨率设置为750*1334
设置Cavans的缩放模式和尺寸
二、设置Button属性
然后我们将Button的位置调整至屏幕的右上方,然后将字体大小放大,文本内容修改为点我(这边大小和文本内容可以根据自己的喜好来调整)
将Button调整到右上方
三、动态创建UGUI对象的原理说明
在开始下面的内容之前,先在这边讲解一下动态创建UGUI对象的原理,我们看看Unity官方文档的介绍说明:(懒得看到大段文字的朋友可以直接跳过这段,看后面的简单说明)
Creating UI elements from scriptingIf you are creating a dynamic UI where UI elements appear, disappear, or change based on user actions or other actions in the game, you may need to make a script that instantiates new UI elements based on custom logic.Creating a prefab of the UI elementIn order to be able to easily instantiate UI elements dynamically, the first step is to create a prefab for the type of UI element that you want to be able to instantiate. Set up the UI element the way you want it to look in the Scene, and then drag the element into the Project View to make it into a prefab.For example, a prefab for a button could be a Game Object with a Image component and a Button component, and a child Game Object with a Text component. Your setup might be different depending on your needs.You might wonder why we don’t have a API methods to create the various types of controls, including visuals and everything. The reason is that there are an infinite number of way e.g. a button could be setup. Does it use an image, text, or both? Maybe even multiple images? What is the text font, color, font size, and alignment? What sprite or sprites should the image use? By letting you make a prefab and instantiate that, you can set it up exactly the way you want. And if you later want to change the look and feel of your UI you can just change the prefab and then it will be reflected in your UI, including the dynamically created UI.Instantiating the UI elementPrefabs of UI elements are instantiated as normal using the Instantiate method. When setting the parent of the instantiated UI element, it’s recommended to do it using the Transform.SetParent method with the worldPositionStays parameter set to false.Positioning the UI elementA UI Element is normally positioned using its Rect Transform. If the UI Element is a child of a Layout Group it will be automatically positioned and the positioning step can be skipped.When positioning a Rect Transform it’s useful to first determine it has or should have any stretching behavior or not. Stretching behavior happens when the anchorMin and anchorMax properties are not identical.For a non-stretching Rect Transform, the position is set most easily by setting the anchoredPosition and the sizeDelta properties. The anchoredPosition specifies the position of the pivot relative to the anchors. The sizeDelta is just the same as the size when there’s no stretching.For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right anchor.Customizing the UI ElementIf you are instantiating multiple UI elements dynamically, it’s unlikely that you’ll want them all to look the same and do the same. Whether it’s buttons in a menu, items in an inventory, or something else, you’ll likely want the individual items to have different text or images and to do different things when interacted with.This is done by getting the various components and changing their properties. See the scripting reference for the Image and Text components, and for how to work with UnityEvents from scripting.
动态创建UGUI对象的方法,简单来说就是将我们需要创建的UGUI对象制作成一个Prefab,然后使用Instantiate方法将其实例化,最后使用相关的API对其属性进行动态设置
四、制作自定义的Text Prefab
接下来我们就来创建自定义的Text Prefab,为动态创建做准备,首先我们会自定义一个如下图所示的Text:
Text效果图
我们来看看这个自定义的Text有哪些内容:
字体的颜色是红色
Text穿创建后会播放一段放大动画
放大动画播放结束后,Text会向上移动一段距离
移动结束后,Text就会消失掉
1、设置MyText属性
清楚了Text所需的内容后,我们首先来新建一个Text对象,并且命名为MyText
新建Text对象
然后我们重置MyText的Rect Transform,重置之后将其宽高分别设置为750和100,接着我们将MyText的字体大小设置为40,颜色设置为红色,然后将对其方式设置为居中:
设置MyText宽高
设置MyText字体属性
2、为Text添加放大动画
MyText的位置和字体属性我们已经设置好了,接下来我们就需要为MyText增加放大和上升两个动画效果了,首先我们选中MyText,然后打开Animation编辑器(Mac版可以使用?+6的快捷键打开)
打开Animation编辑器
然后在Animation编辑器中,点击Create按钮,新建一个动画
新建一个动画
当我们点击Create按钮后,编辑器会弹出一个对话框,我们需要指定新建的Animation的文件名和存放路径,这里我们第一个需要制作的动画是字体出现是的放大效果,所以我们将其命名为Appear,然后为了使资源方便管理,我们将所有的动画资源放入到_Animator的文件夹下面(需要大家自己创建文件夹,关于如何创建可以参见以前的教程)
新建Animation对话框
创建成功后,我们会发现除了我们自己创建的Appear文件,编辑器还自动创建了一个名为MyText的Animator Controller文件,如下图,根据文件类型名字就可以看出,这个文件是用来控制和管理我们Appear这类文件的,像我们需要实现的Text出现后播放放大动画,然后再播放上升动画,这一个过程和逻辑就是通过Animator Controller来实现的,后面我们会讲到
Animator Controller文件
接下来我们回到Animation编辑器里面,在这个里面我们可以对MyText对象的一个属性进行动态变化,从而形成动画效果,Unity对每个对象可以操控的属性变量都列举出来了,这里我们以Text对象来举例,我们点击Add Property按钮,会弹出下级菜单,我们在菜单中可以看到能够操作的属性变量有3大类:
Rect Transform:该类是针对Rect Transform组件的属性进行变化,我们可以改变这些属性来实现对象大小的变化,或者位置的移动等
Text:该类是针对Text组件的属性进行变化,我们可以改变这些属性来实现诸如字体颜色变化,字体显示与否等变化
Animator:该类是对Animator组件的属性进行变化
Add Property按钮
为了实现MyText出现后放大的效果,我们添加Scale属性的变化,由于我们的UI其实是一个平面,对其大小能够产生视觉变化的只有X和Y轴的变化,然后我们在本例中,希望放大效果一共播放0.5秒,其中在0.25秒是MyText放大到1.5倍,所以我们在0.25秒的时候添加一个关键帧,然后将结束的关键帧拖拽至0.5秒处,如下图:
添加关键帧
接着我们选中0.25秒的关键帧,将该帧的Scale.x和Scale.y都设置为1.5
设置缩放变化
接着我们就可以点击Animation编辑器里面的播放按钮,来测试一下动画效果了
放大的动画就做好了,接下里我们继续制作上升的动画效果
3、为Text添加上升动画
首先我们点击Appear按钮,然后选择Create New Clip...,为MyText添加一个新的动画文件:
新建一个动画文件
同样的在弹出的新建对话框中,我们将动画文件的名字命名为UpRight,存放在_Animator文件夹下面:
新建对话框
接着我们在UpRight动画中添加Anchored Position变化:
添加Anchored Position变化
上升动画在本例中,我们希望他能持续1秒,并且上升100个像素,所以我们选中结束的关键帧,在将其Position.y的值设置为100:
Paste_Image.png
然后我们就可以测试一下动画效果是否如我们所预期的:
测试动画效果
好啦,到这一步,我们已经为MyText添加了两个动画,分别是放大效果和上升效果,接下来我们就需要将两个动画衔接起来
4、编排两个动画播放顺序
要编排动画,就需要用到Animator Controller文件,我们双击打开MyText,会自动打开Animator编辑器:
打开MyText文件
Animator编辑器
我们可以通过编辑器内容看到,现在的动画编排状态是MyText一开始就会进入Appear动作,所以要达到我们的预期效果,我们就只需要再添加一条衔接线,让MyText播完Appear后就进入UpRight状态,我们鼠标右键点击Appear状态,然后选择Make Transition,然后连接UpRight状态
链接UpRight状态
接下里我们就可以运行游戏看看动画效果的衔接是否正确了:
测试衔接效果
通过测试我们可以看到,现在MyText出现后会播放放大效果,然后再播放上升效果,但是有一个问题,他会一直循环播放上升效果,所以我们需要将动画的循环播放给关掉
关闭循环播放
这里我们需要将Appear和UpRight两个动画的循环都关掉,关掉之后我们再运行一下游戏,就会发现动画不会循环播放了
5、添加移除脚本
现在我们还存在最后一步,就是MyText上升动画播放完成后,我们需要将MyText删除掉,所以一下我们需要给MyText添加一个脚本,脚本命名为DestroyByTime,由于我们两个动画播放的总时间为1.5秒,所以我添加脚本让MyText生成后的1.5秒就自己销毁掉,下面是脚本的代码内容:
完整的代码
6、制作成Prefab
做完上面这些工作后,我们便可将MyText制作成一个Prefab了,制作方法很简单,直接将MyText拖入到Prefabs文件夹就可以了,这里就不做详细介绍了
五、实现点击Button动态创建一个MyText
首先我们选中最开始创建的Button对象,然后滑动Inspector看到Button (Script)组件的相关属性,我们可以看到其中有一个On Click()属性,这里就是实现Button点击的响应事件的地方
On Click()属性
我们点击其中的+按钮,来新建一个响应事件,我们会看到响应事件有两个部分组成:
新建一个响应事件
上图中我们可以看,左边的Object就是我们需要指定响应的对象,这里的对象可以是我们场景中任意一个GameObject,然后左边的Function就是该对象需要执行的动作,我试着将Button拖入到Object之中:
Button拖入到Object之中
拖入之后,我们就可以看到Function里面有很多动作可以供我们选择,而且Unity还很温馨的给我们按照组件类型来分类了,关于每个动作的含义和用法,感兴趣的朋友可以自己去查阅官方文档,本例中,我们需要的动作是没有的,所以我们需要自己创建一个动作
1、创建我们自己的响应动作
首先我们给Button添加一个脚本,命名为MyButtonEvent,然后输入一下代码:
完整的代码
首先我们引入UnityEngine.UI命名空间
然后我们声明一个公共变量myText,用来存放我们的MyText Prefab
然后我们定义一个私有的tempText,用来临时保存生成的MyText实例
然后我们定义了一个公共的方法createMyText,这里方法必须是Public的,这样才能出现在Function选项中
方法里面我们首先使用Instantiate方法动态创建了一个MyText的对象,然后我们将他赋值给tempText
由于UGUI对象只能处于Cavans下面才能被显示出来,所以我们需要将创建的MyText实例的父节点设置为Canvas,使用的是SetParent方法,该方法属于Transform组件
然后我们再动态修改Text的文本内容
写完代码,保存一下,然后回到编辑器
2、选择响应动作
此时我们选中Button对象,我们可以在On Click()中找到我们刚刚创建的createMyText动作(或者叫方法),如下图:
createMyText动作
我们选中它之后,我们可以设置传递给方法的参数,也就是我们MyText的文本内容,我们将内容设置为你好Unity!
设置传递参数
做完这个操作,然后我们再把创建中现有的MyText对象删除掉,运行一下游戏,点击Button就会弹出一个MyText对象了
打赏1块,支持原创!
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮
被以下专题收入,发现更多相似内容:
如果你是程序员,或者有一颗喜欢写程序的心,喜欢分享技术干货、项目经验、程序员日常?事等等,欢迎投稿《程序员》专题。
专题主编:小...
? 194908人关注
玩转简书的第一步,从这个专题开始。
想上首页热门榜么?好内容想被更多人看到么?来投稿吧!如果被拒也不要灰心哦~入选文章会进一个队...
? 136090人关注
? 2063人关注
打赏1块,支持原创!
选择支付方式:判断鼠标是否点击在UGUI上
#if UNITY_ANDROID && !UNITY_EDITOR
#define ANDROID
#if UNITY_IPHONE && !UNITY_EDITOR
#define IPHONE
using UnityE
using UnityEngine.UI;
using System.C
using UnityEngine.EventS
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
void Update()
if (Input.GetMouseButtonDown(0)||(Input.touchCount &0 && Input.GetTouch(0).phase == TouchPhase.Began))
#if IPHONE || ANDROID
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
if (EventSystem.current.IsPointerOverGameObject())
Debug.Log("当前触摸在UI上");
Debug.Log("当前没有触摸在UI上");
方法来自:/archives/3327
阅读(...) 评论()Unity3D(150)
UGUI - 判断是否点击在UI 上 Bug,在移动输入模式检测失败
转载请保留原文链接:
UGUI 提供了一个检测是否点击在UI上的方法
EventSystem.current.IsPointerOverGameObject();
在EventSystem的标准输入Standalone Input Model下是正常的,
但是在Touch Input Module输入模式下不正常
参考网络资料,解决办法(直接上):
//UGUI 提供了一个检测是否点击在UI上的方法
//EventSystem.current.IsPointerOverGameObject();
//但是该方法在PC上检测正常,结果拿到Android真机测试上,永远检测不到。
//方法一, 使用该方法的另一个重载方法,使用时给该方法传递一个整形参数
// 该参数即使触摸手势的 id
// int id = Input.GetTouch(0).fingerId;
//public static bool IsPointerOverGameObject(int fingerID) {
return UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(fingerID);//移动输入模式下一样不行
public static bool IsPointerOverGameObject() {
//if (Input.touchCount & 0) {
int id = Input.GetTouch(0).fingerId;
return UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(id);//安卓机上不行
//return UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject();
PointerEventData eventData = new PointerEventData(UnityEngine.EventSystems.EventSystem.current);
eventData.pressPosition = Input.mouseP
eventData.position = Input.mouseP
List&RaycastResult& list = new List&RaycastResult&();
UnityEngine.EventSystems.EventSystem.current.RaycastAll(eventData, list);
//Debug.Log(list.Count);
return list.Count & 0;
//方法二 通过UI事件发射射线
//是 2D UI 的位置,非 3D 位置
public static bool IsPointerOverGameObject(Vector2 screenPosition) {
//实例化点击事件
PointerEventData eventDataCurrentPosition = new PointerEventData(UnityEngine.EventSystems.EventSystem.current);
//将点击位置的屏幕坐标赋值给点击事件
eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);
List&RaycastResult& results = new List&RaycastResult&();
//向点击处发射射线
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count & 0;
//方法三 通过画布上的 GraphicRaycaster 组件发射射线
public bool IsPointerOverGameObject(Canvas canvas, Vector2 screenPosition) {
//实例化点击事件
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
//将点击位置的屏幕坐标赋值给点击事件
eventDataCurrentPosition.position = screenP
//获取画布上的 GraphicRaycaster 组件
GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent&GraphicRaycaster&();
List&RaycastResult& results = new List&RaycastResult&();
// GraphicRaycaster 发射射线
uiRaycaster.Raycast(eventDataCurrentPosition, results);
return results.Count & 0;
网友解决办法:
/// &summary&
/// Cast a ray to test if Input.mousePosition is over any UI object in EventSystem.current. This is a replacement
/// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3
/// &/summary&
private static bool IsPointerOverUIObject()
if (EventSystem.current == null)
return false;
// the ray cast appears to require only eventData.position.
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List&RaycastResult& results = new List&RaycastResult&();
/// Cast a ray to test if screenPosition is over any UI object in canvas. This is a replacement
/// &/summary&
return false;
// Referencing this code for GraphicRaycaster /stramit/ead7ca1f432f3c0f181f
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
List&RaycastResult& results = new List&RaycastResult&();
return results.Count & 参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:168678次
积分:3035
积分:3035
排名:第8458名
原创:68篇
转载:186篇
译文:36篇
评论:69条
(1)(4)(22)(23)(13)(30)(2)(40)(11)(3)(3)(22)(35)(14)(21)(1)(1)(1)(6)(3)(34)(1)UGUI判断鼠标或手指(移动平台)是否点击在UGUI上
很多的时候我们要判断时候都点中UGUI&此时要加命名空间 using UnityEngine.EventS有的时候新建脚本并不能直接用 UGUI &此时也要加命名空间 &using UnityEngine.UI;接下来就是判断是否点击在UGUI上了 ,上代码//Windows 上&if (Input.GetMouseButtonDown(0))& & & & & & {& & & & & & & & Debug.Log(EventSystem.current.gameObject.name);& & & & & & & & if (EventSystem.current.IsPointerOverGameObject())& & & & & & & & {& & & & & & & & & & Debug.Log(&当前触摸在UI上&);& & & & & &&& & & & & & & & }& & & & & & & & else& & & & & & & & {& & & & & & & & &&& & & & & & & & & & Debug.Log(&当前没有触摸在UI上&);& & & & & & & && & & & & & & & }& & & & & & }//安卓上& if (Input.touchCount & 0 && Input.GetTouch(0).phase == TouchPhase.Began)& & & & & & {& & & & & & & & if (IsPointerOverGameObject(Input.GetTouch(0).fingerId))& & & & & & & & {& & & & & & & & & & Debug.Log(&Hit UI, Ignore Touch&);& & & & & & & && & & & & & & & }& & & & & & & & else& & & & & & & & {& & & & & & & && & & & & & & & & & Debug.Log(&Handle Touch&);& & & & & & & & }& & & & & & }
最新教程周点击榜
微信扫一扫

参考资料

 

随机推荐