• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

#私藏项目实操#愚公系列2022年02月 U3D全栈班 013-使用脚本操纵对象案例

武飞扬头像
愚公搬代码
帮助1

前言

使用C#脚本控制游戏对象,是一项必备的基本技能。Unity3D可以使用的脚本有C#和javascript等。我们主要讲注意力集中在C#上。本文将会介绍怎样使用脚本控制场景中的游戏对象。

一、使用脚本操纵对象案例

使用脚本操纵对象分4步走

  1. tep1: 创建脚本
  1. tep2:声明对象
  2. tep3:实例化绑定
  3. tep4:操作

以下是实际流程案例:
1、新建一个脚本,将脚本以组件的形式挂载到场景中任何游戏对象身上

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

public class Ryunm_ScriptsInUnity : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    //每帧都会执行一次
    void Update()
    {
    }
    public void FirstBtn_OnClick()
    {

    }
}

学新通

2、脚本中声明一个Gameobject对象命名firstObj;声明一个Sprite对象命名firstSprite

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

public class Ryunm_ScriptsInUnity : MonoBehaviour
{
    public GameObject firstObj;
    public Sprite firstSprite;

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

    }

    // Update is called once per frame
    //每帧都会执行一次
    void Update()
    {
    }
    public void FirstBtn_OnClick()
    {

    }
}

3、场景中添加一个2D Sprite的GameObject,并对脚本中声明的firstObj/ firstSprite对象进行绑定(实例化)

学新通学新通

4、场景中添加UI Button按钮,Text文本,在脚本中自定义Public方法命名为FirstOnClick(),方法内容
a.通过Transform组件修改游戏对象的位置;
b. 用UI Text显示x坐标位置信息;
c.设置2D Sprite的SpriteRenderer组件中的Sprite属性的值为firstSprite

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

public class Ryunm_ScriptsInUnity : MonoBehaviour
{
    public GameObject firstObj;
    public Sprite firstSprite;

    public Text _text;//step1

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

    }

    // Update is called once per frame
    //每帧都会执行一次
    void Update()
    {

    }
    public void FirstBtn_OnClick()
    {
        //1、将firstObj的SpriteRenderer绑定资源图片
        firstObj.GetComponent<SpriteRenderer>().sprite = firstSprite;//1
        //2、通过Transform组件修改位置
        firstObj.transform.position  = Vector3.up;//2
        //3、让Text显示位置信息
        _text.text = firstObj.transform.position.ToString();//3
    }
}

5、给按钮绑定事件FirstOnClick()

学新通

总结

通过此案例游戏开发基本是脚本控制游戏对象的操作,而且脚本就是组件。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhicjbfj
系列文章
更多 icon
同类精品
更多 icon
继续加载