Unity3d 基础学习

First Post:

Last Update:

Word Count:
2k

Read Time:
10 min

Unity3d 基础学习

注: 本片文章记录自己遇到的一些问题,还有学习记录。

doc: https://docs.unity3d.com/Manual/

asset store: https://assetstore.unity.com/

如何使用Unity3d构建一个Android程序

安装好引擎之后,确保有Android Sdk,这个直接从UnityHub中下载即可,创建一个项目,随便拖拖场景,选择File->Build Settings-> Android -> Switch-> Build。点击Build后,选择一个路径保存即可。编译完毕后,可以看到选择的文件夹下出现一个apk文件。

如何修改启动场景

File->Build Settings -> Scenes In Build

选择你的场景即可。

如何打印日志

1
Debug.Log("My name is " + "i0gan");   

如何修改Transform组件属性

1
transform.position = new Vector3(x, 0, 0);

Button点击事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Click_Settings : MonoBehaviour
{
void Awake () {
Button button = gameObject.GetComponent<Button>() as Button;// 获取Button组件
button.onClick.AddListener(ClickedSettings);// 为button的OnClick事件添加监听器,当监听到Click事件时,回调ClickedSettings函数。
}
// Start is called before the first frame update
void Start()
{

}

void ClickedSettings() {
Debug.Log("Hello world");
}

// Update is called once per frame
void Update()
{

}
}

跨脚本调用

1
2
3
GameObject go = GameObject.Find(“somegameobjectname”);
ScriptB other = (ScriptB) go.GetComponent(typeof(ScriptB));
other.DoSomething();

ref: https://www.pianshen.com/article/5019397567/

ref: https://www.jianshu.com/p/b0d5504a12a4

键盘按下

ref: https://www.cnblogs.com/1138720556Gary/p/9652350.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void Update()
{
if(Input.GetKey(KeyCode.UpArrow))
{
Vector3 newPos = transform.position;
newPos.y += speed;
transform.position = newPos;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
Vector3 newPos = transform.position;
newPos.y -= speed;
transform.position = newPos;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
Vector3 newPos = transform.position;
newPos.x -= speed;
transform.position = newPos;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
Vector3 newPos = transform.position;
newPos.x += speed;
transform.position = newPos;
}
}

设置横屏

File->Player Settings -> Player -> Settings for Android -> Resolution and Presentation -> Default Orientation

或者

Edit->Project Settings -> Settings for Android -> Resolution and Presentation -> Default Orientation

ref: https://blog.csdn.net/Wenhao_China/article/details/110328045

使UI跟随屏幕分辨率变化自适应

设置Canvas对象的Canvas Scaler ->UI Scale Mode为Scale With Screen Size

https://blog.csdn.net/qq_15020543/article/details/82595179

切换场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;//首先要记得引用命名空间

public class ChangeSceneTest : MonoBehaviour
{
    //在unity中 File->Build Settings->把要切换的场景添加到Scenes In Build下面,也可以Add Open Scenes
    //把该脚本的方法添加到场景中切换场景按钮上面的Button->OnClick
   public void OnClick()
    {
        SceneManager.LoadScene("SceneName");//要切换到的场景名
    }
}

播放视频

ref: https://blog.csdn.net/yangwenjie16/article/details/80746699

如何实现控制脚本

创建一个空对象,在此空对象上挂在脚本,若想控制其他对象,在脚本中创建所要控制对象的变量,在可视化视图中拖进该变量中。

如:

1
public InputField textInput;

定义好之后,可视化界面赋值即可。

如何通过Button按钮触发脚本的函数

在某脚本中定义好函数后,在Button的可视化界面,在Button->Click下添加一个对象,在视图中选择所要触发的函数即可。

设置后台运行

Settings for PC, Mac & Linux Standalone -> Run In Background

没有声音

1
There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene

解决

添加一个audio listener组件在Camara里

ref: https://forum.unity.com/threads/there-are-no-audio-listeners-in-the-scene-thats-actually-fine-right.384596/

如何停顿5秒执行一个方法

nvoke方法可以制定一个函数延迟调用。

1
2
3
void  TestFunc {
Debug.Log( "Test" );
}

5秒调用上面的TestFunc函数,可以这样

1
Invoke( "TestFunc" , 5f);

每隔几秒重复执行一段代码

1
2
3
void Start () {
  StartCoroutine("DoSomething");
}
1
2
3
4
5
6
7
IEnumerator DoSomething () {
  while (true) {
   //需要重复执行的代码就放于在此处
   print("DoSomething Loop");
   yield return new WaitForSeconds (1);
  }
}

ref: https://blog.csdn.net/yf391005/article/details/94732900?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase

资源获取

https://blog.csdn.net/weixin_41814169/article/details/88181762

https://github.com/764424567/Unity-plugin

加载场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ClickBack : MonoBehaviour
public void Click_Back() {
StartCoroutine(Load());

IEnumerator Load()

AsyncOperation op = SceneManager.LoadSceneAsync("index");
yield return new WaitForEndOfFrame();
op.allowSceneActivation = true;


ref: https://gameinstitute.qq.com/community/detail/129045

退出游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class QuitScene : MonoBehaviour {
    
    void Update () {
        if (Input.GetKeyDown(KeyCode.Escape)){//按下ESC键则退出游戏
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
        }

    }
}

ref: https://blog.csdn.net/qq_39225721/article/details/90599047

设置图片全屏

https://www.tqwba.com/x_d/jishu/143511.html

Unity调用摄像头获取拍摄画面 1

ref: https://blog.csdn.net/sinat_34791632/article/details/78261893

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System.Collections;
using UnityEngine;
public class Test : MonoBehaviour
{
public WebCamTexture cameraTexture;
public string cameraName = "";
private string isUser;
private MeshRenderer renderer;
void Start()
{
renderer = this.GetComponent<MeshRenderer>();
StartCoroutine(Test1());
}
IEnumerator Test1()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
bool isUser = Application.HasUserAuthorization(UserAuthorization.WebCam);
isUser = false;
if (!isUser)
{
WebCamDevice[] devices = WebCamTexture.devices;
cameraName = devices[0].name;
cameraTexture = new WebCamTexture(cameraName, 1024, 768,30);
cameraTexture.Play();
renderer.material.mainTexture = cameraTexture;
}
}
}

Unity调用摄像头获取拍摄画面 2

获取设备信息

ref: https://blog.csdn.net/weixin_34162629/article/details/93687008

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using UnityEngine;  
using System.Collections;
public class GetSystemInfo : MonoBehaviour {

string systemInfo;
// Use this for initialization
void Start() {
systemInfo = "\tTitle:当前系统基础信息:\n设备模型:" + SystemInfo.deviceModel + "\n设备名称:" + SystemInfo.deviceName + "\n设备类型:" + SystemInfo.deviceType +
"\n设备唯一标识符:" + SystemInfo.deviceUniqueIdentifier + "\n显卡标识符:" + SystemInfo.graphicsDeviceID +
"\n显卡设备名称:" + SystemInfo.graphicsDeviceName + "\n显卡厂商:" + SystemInfo.graphicsDeviceVendor +
"\n显卡厂商ID:" + SystemInfo.graphicsDeviceVendorID + "\n显卡支持版本:" + SystemInfo.graphicsDeviceVersion +
"\n显存(M):" + SystemInfo.graphicsMemorySize + "\n显卡像素填充率(百万像素/秒),-1未知填充率:" + SystemInfo.graphicsPixelFillrate +
"\n显卡支持Shader层级:" + SystemInfo.graphicsShaderLevel + "\n支持最大图片尺寸:" + SystemInfo.maxTextureSize +
"\nnpotSupport:" + SystemInfo.npotSupport + "\n操作系统:" + SystemInfo.operatingSystem +
"\nCPU处理核数:" + SystemInfo.processorCount + "\nCPU类型:" + SystemInfo.processorType +
"\nsupportedRenderTargetCount:" + SystemInfo.supportedRenderTargetCount + "\nsupports3DTextures:" + SystemInfo.supports3DTextures +
"\nsupportsAccelerometer:" + SystemInfo.supportsAccelerometer + "\nsupportsComputeShaders:" + SystemInfo.supportsComputeShaders +
"\nsupportsGyroscope:" + SystemInfo.supportsGyroscope + "\nsupportsImageEffects:" + SystemInfo.supportsImageEffects +
"\nsupportsInstancing:" + SystemInfo.supportsInstancing + "\nsupportsLocationService:" + SystemInfo.supportsLocationService +
"\nsupportsRenderTextures:" + SystemInfo.supportsRenderTextures + "\nsupportsRenderToCubemap:" + SystemInfo.supportsRenderToCubemap +
"\nsupportsShadows:" + SystemInfo.supportsShadows + "\nsupportsSparseTextures:" + SystemInfo.supportsSparseTextures +
"\nsupportsStencil:" + SystemInfo.supportsStencil + "\nsupportsVertexPrograms:" + SystemInfo.supportsVertexPrograms +
"\nsupportsVibration:" + SystemInfo.supportsVibration + "\n内存大小:" + SystemInfo.systemMemorySize;

}

// Update is called once per frame
void OnGUI() {
GUILayout.Label(systemInfo);
}
}

处理json [LitJson]

ref: https://www.cnblogs.com/gss0525/p/10209715.html

ref: https://litjson.net/docs/quickstart/mapping-json-to-objects

download: https://github.com/LitJSON/litjson/releases

下载之后,将src下的LitJson文件复制到Plugins目录下

例子:

1

处理json 其他 [NewtonsoftJson]

ref: https://blog.csdn.net/youxijishu/article/details/104348151

本次示例使用的Unity3d版本是2019.3.1f1,NewtonsoftJson的版本tag是8.0.3,它的github地址是:https://github.com/JamesNK/Newtonsoft.Json/tree/8.0.3

注意,网上很多示例都是导入它的dll文件,这样在unity3d编辑器里面使用是没有问题的,但是如果发布成安卓包就会有异常。所以要把NewtonsoftJson项目中src下面的Newtonsoft.Json中的原文件整个添加到unity3d的Plugins目录下,如图所示:

随机背景图片生成

ref: https://blog.csdn.net/zhang_by0_0/article/details/110800642

储存数据

ref: https://blog.csdn.net/yeluo_vinager/article/details/50074461

SendMessage

ref: https://blog.csdn.net/weixin_38109688/article/details/78420875

Unity 从Resources中动态加载Sprite图片

ref: https://blog.csdn.net/wks310/article/details/86061768

ref: https://blog.csdn.net/u013509878/article/details/80060108

OnMouseEnter

ref: https://blog.csdn.net/qq_33781669/article/details/88123611

Unity中GUITexture过时,guiTexture.texture

将GUITexture替换为RawImage即可

ref: https://www.zhihu.com/question/401983080

ParticleEmitter旧粒子系统退役 2018新粒子系统

ParticleEmitter -> ParticleSystem

particleEmitter.emit -> gameObject.GetComponent().enableEmission

ref: https://blog.csdn.net/qq258456qq/article/details/102569269

UILabel找不到

替换为Text即可(自我发现)。

The UILabel class you are looking for is likely part of NGUI.

Import NGUI into your current project from the asset store (assuming you’ve bought it) and Unity will find the class.

ref: https://stackoverflow.com/questions/19419251/uilabel-could-not-be-found

安装NGUI插件与使用

官网下载: http://tasharen.com/

ref: https://blog.csdn.net/gtncwy/article/details/37651971

ref: https://www.jianshu.com/p/5d6509506443

UnityEngine.Mesh’ does not contain a definition for GetTriangleStrip’

把GetTriangleStrip改成GetTriangles,对应着SetTriangleStrip也要改成SetTriangles

ref: https://blog.csdn.net/some_man/article/details/76223434

Unity + Vscode代码补全

在vscode安装如下插件

Debugger for unity

Unity Tools

Unity Code Snippets

Unity Snippets

ref: https://blog.csdn.net/qq_38876313/article/details/107935382

Unity游戏自更新

ref: https://www.cnblogs.com/yfceshi/p/6963923.html

打赏点小钱
支付宝 | Alipay
微信 | WeChat