Unity C#代码入门

1. 脚本基本结构

1.1 unity生成的模板

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//设置初始值,相当于构造函数
} // Update is called once per frame
void Update()
{
//不停循环执行的代码
}
}

1.2 常用的注解属性

[SerializeField]
float moveSpeed = 8; Debug.Log("Celling");//控制台输出 other.gameObject.tag == "Celling"//获得tag

csharp如果不标明类别, 默认pravite

加上SerializeField, 能让pravite的变量, 在unity右侧直接调节

Time.deltaTime

不同的机器, 游戏帧数不同, Time.deltaTime可以让机器用相同的帧数执行

1.3 常见的类

类名 解释
Text 得到UI的text(需要导入using UnityEngine.UI;)
Animator 动画
SpriteRenderer 渲染器(改变物体的外观?)
GameObject 获取游戏内物体

2. 源码解析

public class Player : MonoBehaviour
{
//类名必须一致 }

2.1 初始值定义

 void Start()
{ HP = 10;
score = 0;
scoreTime = 0f;
anim = GetComponent<Animator>();
render = GetComponent<SpriteRenderer>();
deathSound = GetComponent<AudioSource>(); }

GetComponent();获得的是当前类的组件AudioSource, 由于获取的是类的引用, 因此可以改变类的属性.

2.2 循环执行函数

void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(moveSpeed * Time.deltaTime, 0, 0);
render.flipX = false;
anim.SetBool("run", true);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(-moveSpeed * Time.deltaTime, 0, 0);
render.flipX = true;
anim.SetBool("run", true); }
else
{
anim.SetBool("run", false);
} UpdateScore();
}

2.2.1 键盘监听函数

Input.GetKey(KeyCode.RightArrow) //输入的是右边箭头

2.2.2 变换属性 transform

​ transform.Translate(moveSpeed * Time.deltaTime, 0, 0);

将向x轴移动一定的距离

其实就是右侧的这些属性, 因此Rotation旋转, Scale缩放都能调整

render.flipX = false;

GetComponent<SpriteRenderer>().flipX = false;

同理:

 anim.SetBool("run", true);

GetComponent<Animator>().SetBool("run", true);

动画也是如此

当然动画要复杂些

2.3 碰撞函数

void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Normal")
{
if (other.contacts[0].normal == new Vector2(0f, 1f))
{
currentFloor = other.gameObject;
ModifyHp(1);
other.gameObject.GetComponent<AudioSource>().Play();
Debug.Log("floor1");
} }
else if (other.gameObject.tag == "Nails")
{
if (other.contacts[0].normal == new Vector2(0f, 1f))
{
currentFloor = other.gameObject;
ModifyHp(-2);
Debug.Log("floor2");
anim.SetTrigger("hurt");
other.gameObject.GetComponent<AudioSource>().Play();
}
}
else if (other.gameObject.tag == "Celling")
{
if (other.contacts[0].normal == new Vector2(0f, -1f))
{ currentFloor.GetComponent<BoxCollider2D>().enabled = false;
ModifyHp(-2);
Debug.Log("Celling");
anim.SetTrigger("hurt");
other.gameObject.GetComponent<AudioSource>().Play();
}
} }

所谓碰撞就是, 遇到other这个物体会和它发生物理效果, 而不是穿过

2.3.1 碰撞检测精确到边

other.contacts[0].normal == new Vector2(0f, 1f)
//normal就是法向量

2.4 穿过函数

void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "DeadLine")
{
ModifyHp(-12);
Die();
}
}

2.5 操作子组件

void UpdateHpBar()
{
for (int i = 0; i < HpBar.transform.childCount; i++)
{
if (HP > i)
{
HpBar.transform.GetChild(i).gameObject.SetActive(true);
}
else
{
HpBar.transform.GetChild(i).gameObject.SetActive(false); }
}
}

主要是对gameObject的操作

3. 常用函数

3.1 结束游戏

void Die()
{
deathSound.Play();
Time.timeScale = 0f; //时间静止
btnReplay.SetActive(true);
}

3.2 重启游戏

//需要使用以下命名空间
using UnityEngine.SceneManagement;
public void Replay()
{
Time.timeScale = 1;
/*重新加载场景*/
SceneManager.LoadScene("SampleScene");
}

3.3 销毁物体

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Floor : MonoBehaviour
{
[SerializeField] float moveSpeed = 1f; // Start is called before the first frame update
void Start()
{ } // Update is called once per frame
void Update()
{
transform.Translate(0,moveSpeed * Time.deltaTime,0);
if(transform.position.y>=4.7f)
{
Destroy(gameObject);
transform.parent.GetComponent<FloorManager>().SpwanFloor();
} }
}

3.4 生成新的物体

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class FloorManager : MonoBehaviour
{
[SerializeField] GameObject[] floorPerfabs;
public void SpwanFloor()
{
int r = Random.Range(0,2);
GameObject floor = Instantiate(floorPerfabs[r],transform);
floor.transform.position = new Vector3(Random.Range(-3.8f,3.8f),-5,0);
}
}

Unity C#代码入门的更多相关文章

  1. Unity实现代码控制音频播放

    前言 很久没说过Unity了,现在说一下Unity用代码控制音频播放 准备工作 1.需要播放的音频 2.给需要加声音的对象加Audio Source组件 3.新建Play脚本,并绑定需要播放声音的对象 ...

  2. unity对话代码

    这个是根据网上unity GUI打字机教程修改的 原教程是JS,我给改成了C#,然后增加了许多功能 这个教程能实现一段文字对话,有打字机显示效果,能写许多对话,能快进对话,总之现在RPG游戏里有的功能 ...

  3. 微软IOC容器Unity简单代码示例3-基于约定的自动注册机制

    @(编程) [TOC] Unity在3.0之后,支持基于约定的自动注册机制Registration By Convention,本文简单介绍如何配置. 1. 通过Nuget下载Unity 版本号如下: ...

  4. 微软IOC容器Unity简单代码示例2-配置文件方式

    @(编程) 1. 通过Nuget下载Unity 这个就不介绍了 2. 接口代码 namespace UnityDemo { interface ILogIn { void Login(); } } n ...

  5. 微软IOC容器Unity简单代码示例1

    @(编程) 1. 通过Nuget下载Unity 这个就不介绍了 2. 接口代码 namespace UnityDemo { interface ILogIn { void Login(); } } 3 ...

  6. 千行代码入门Python

    这个是从网上找到的一份快速入门python的极简教程,大概一千行左右,个人觉得不错,特此收藏以备后用. # _*_ coding: utf-8 _*_ """类型和运算- ...

  7. ue4 代码入门

    官网:暴露游戏元素给蓝图 https://docs.unrealengine.com/latest/CHN/Engine/Blueprints/TechnicalGuide/ExtendingBlue ...

  8. Tensorflow MNIST 数据集测试代码入门

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/50614444 测试代码已上传至GitH ...

  9. Tensorflow MNIST 数据集測试代码入门

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/50614444 測试代码已上传至GitH ...

  10. 使用rider做为unity的代码编辑器

    使用Rider做的编写Unity代码的IDE,记录一些与VS不相同的笔记 安装和设置方法: 我使用Rider 2019.1 + Unity3D 2018.3.4,在安装完Rider之后,在Unity中 ...

随机推荐

  1. 【springboot】约定优于配置

    spring的核心思想:约定优于配置 @SpringBootApplication这个注解的本质是有以下三个注解 1.@SpringBootConfiguration 表示该类是一个配置类 2.@En ...

  2. 深入理解 epoll 原理

    从网卡如何接收数据说起 CPU 如何知道接受了数据? 进程阻塞为什么不占用 CPU 资源? 工作队列 等待队列 唤醒进程 内核接收网络数据全过程 同时监视多个 socket 的方法 select 的监 ...

  3. Outlook怎么合并相同邮件?设置Outlook邮件为对话模式

    选择View->勾选"Show as Conversations", 这样同一个标题的邮件就是叠在一块显示了. 不蟹,bro.

  4. (转载)私人问卷收集系统-Surveyking问卷收集系统

    前言 但凡提及问卷收集系统,问卷星与腾讯问卷通常都为大家首选问卷调查系统. 担心数据安全,海量问卷管理不便,工作流创建困难?快速部署自有问卷调查系统开始你的问卷调查之旅. 无论是问卷调查,考试系统,公 ...

  5. 使用 p7zip 加密解密

    1. 安装 yum install p7zip p7zip-plugins 2. 加密打包 7z a -ptest test.7z test.php -p 密码 test.php 可以是目录 或者 多 ...

  6. Docker宿主机agetty进程cpu占用率100% 问题

    参考  https://blog.51cto.com/u_15450131/4751959 systemctl stop getty@tty1.service systemctl mask getty ...

  7. MySQL同步部分库注意的问题

    同步部分库或部分库表 复制部分库:replicate_do_db 复制排除部分库:replicate_ignore_db 复制部分表:replicate_do_table 复制排除部分表:replic ...

  8. ASP.NET Core 6部署到IIS

    1.打开IIS,新建一个网站 2.给新创建的应用程序池,设置为无托管代码,下面那个选经典或集成好像都没问题 3.运行网站,不出意外的话,会报错,提示HTTP 错误 500.19,说明网站目录权限不足, ...

  9. iOS底层原理01:源码探索的三种方式

    ios 开发探索源码三种方法 1.下符号断点的形式直接跟流程 2.通过摁住 control + step  into 3.汇编查看跟流程 1.符号断点直接跟流程 以alloc为例: 选择断点Symbo ...

  10. JS实现另存/打印功能

    代码实现 <div id="main"> <-- 需要保存的内容 --></div> <div @click="printdiv ...