小编Pro*_*mer的帖子

从 url 加载和显示图像

我正在尝试将图像从 url 加载到 GameObject。

我找到了下一个教程:

https://www.youtube.com/watch?v=8UK2EsKBzv8

下载成功,但是看不到图片。

我究竟做错了什么?

// Use this for initialization
void Start () {
    StartCoroutine(loadSpriteImageFromUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png"));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{
    // Check internet connection
    if (Application.internetReachability == NetworkReachability.NotReachable)
    {
        yield return null;
    }

    var www = new WWW(URL);
    Debug.Log("Download image on progress");
    yield return www;

    if (string.IsNullOrEmpty(www.text))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);                      
        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height),      
            Vector2.one / 2);                                     

        GetComponent<SpriteRenderer>().sprite = sprite; …
Run Code Online (Sandbox Code Playgroud)

c# url image unity-game-engine

3
推荐指数
1
解决办法
9047
查看次数

Application.persistentDataPath在构建中的位置

当我从编辑器运行游戏并保存加载数据时,我发现数据在:C:\Users\User\AppData\LocalLow\DefaultCompany\projectname\data.

当我构建它并获得可执行文件时,该数据仍可正常加载,但如果我保存并重新启动,则不会保存.但是当我从编辑器中启动它时它会这样做.

这是我的代码中的错误,还是我不从Unity Editor运行它的其他地方的文件?

稍后当我导出游戏以启动游戏时,我会拥有持久数据I Json文件,这些文件必须与游戏一起使用才能运行.

为清楚起见,这里是处理Json的保存/加载的类:

public class DataHandler
{
    //Save Data
    public static void saveData<T>(T dataToSave, string dataFileName)
    {
        string tempPath = Path.Combine(Application.persistentDataPath, "data");
        tempPath = Path.Combine(tempPath, dataFileName + ".txt");

        //Convert To Json then to bytes
        string jsonData = JsonUtility.ToJson(dataToSave, true);
        byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);

        //Create Directory if it does not exist
        if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
        }
        //Debug.Log(path);

        try
        {
            File.WriteAllBytes(tempPath, jsonByte);
            Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
        }
        catch (Exception e)
        { …
Run Code Online (Sandbox Code Playgroud)

c# json unity-game-engine unity5

3
推荐指数
1
解决办法
1万
查看次数

将UI RectTransform移动到世界位置

我有一个名为Player的GameObject 和一个Canvas。该HealthBar游戏对象是画布的孩子(画布> HealthBar) 。在播放器后面有脚本的HP酒吧。它应该跟随玩家在其上方的固定位置,因此它位于精灵顶部附近。这是HP Follow Script的“关注”部分。

        void Update () 
{
    Vector3 currentPos = transform.position;
    Vector3 playerPos = Camera.main.WorldToViewportPoint (Player.transform.position);
    transform.position = playerPos;
Run Code Online (Sandbox Code Playgroud)

问题是HP条随角色移动,但移动速度却很小。例如,如果玩家移动一个单位,则小节移动0.1个单位。

错误视频:https//streamable.com/vaz7h

c# canvas unity-game-engine

3
推荐指数
1
解决办法
1万
查看次数

使用PlayOneShot时如何停止音频

所以目前我有一个8秒长的音频剪辑。但是,我希望能够在发生特定情况时停止播放。像这样:

private AudioSource soundPlayer2D;
private AudioClip sound;  

     void Start(){

     GameObject new2DsoundPlayer = new GameObject ("2DSoundPlayer");
     soundPlayer2D = new2DsoundPlayer.AddComponent<AudioSource> (); 
     new2DsoundPlayer.transform.parent = transform;

     }
     void Update() {

        if(shouldPlayAudio){

        soundPlayer2D.PlayOneShot (sound, fxVolumePercentage * allVolumePercentage);

        } else if(shouldStopAudio){

        //Stop Audio <--

        }
     }
Run Code Online (Sandbox Code Playgroud)

编辑1:注意,我只想停止特定的音频剪辑,而不是音频源

c# audio unity-game-engine

3
推荐指数
1
解决办法
4377
查看次数

Vector3.Set 和 Rigidbody2D.velocity.Set 和功能无法正常工作

bodyis的简单移动脚本中gameObject.GetComponent<Rigidbody2D> (),此代码应用移动

body.velocity = new Vector2 (10 * dir, body.velocity.y);
Run Code Online (Sandbox Code Playgroud)

然而,在这一个没有运动(也没有错误)出现

body.velocity.Set (10 * dir, body.velocity.y);
Run Code Online (Sandbox Code Playgroud)

我在Unity 文档中没有看到任何解释。你能解释为什么body.velocity.x在第二种情况下仍然为零吗?

c# properties unity-game-engine

3
推荐指数
1
解决办法
1343
查看次数

使游戏对象在编辑器窗口中不可选择

我的场景中有一个淡入淡出面板gameobject,它必须位于所有其他游戏对象之上。但是,当我单击编辑器窗口中的某个对象时,由于该对象gameobject位于所有对象之上,因此是在层次结构中自动选择的对象。

有没有办法将 保持gameobject在画布顶部,就像现在一样,但当我单击场景时使其完全不可选择?

c# unity-game-engine

3
推荐指数
1
解决办法
2249
查看次数

什么导致Unity内存泄漏?

我在使用以下代码时遇到了 Unity 内存泄漏:

行为:在运行时,Unity 最终使用 > 64GB 的 RAM 并崩溃(这就是这台机器所拥有的)

场景:我的场景中只有一架飞机,代码如下。

我该如何解决?我不认为我想要这里的弱引用(或者至少在 C++ 中我不会在这种情况下使用weak_ptr,也许是unique_ptr)。我只想在对象超出范围时释放内存。

void Start () {
    frameNumber_ = 0;

    // commented code leaks memory even if update() is empty
    //WebCamDevice[] devices = WebCamTexture.devices;
    //deviceName = devices[0].name;
    //wct = new WebCamTexture(deviceName, 1280, 720, 30);
    //GetComponent<Renderer>().material.mainTexture = wct;
    //wct.Play();

    wct = new WebCamTexture(WebCamTexture.devices[0].name, 1280, 720, 30);
    Renderer renderer = GetComponent<Renderer>();
    renderer.material.mainTexture = wct;
    wct.Play();
}

// Update is called once per frame
// This code in update() also leaks memory …
Run Code Online (Sandbox Code Playgroud)

c# unity-game-engine

3
推荐指数
1
解决办法
4844
查看次数

没有GameObject.Find找到Gameobjects的更好方法

使用Unity,我正在开发一款游戏,所有Gameobjects带有某个标签的游戏都会定期消失/重新出现(平均每10秒钟).我GameObject.FindGameObjectsWithTag()用来创建一个Gameobject[]通过我每次枚举对象需要可见/不可见的通过.我不能在Start上调用它一次,因为Gameobjects在播放时会创建新的.我认为Gameobject[]每次创建/销毁某些内容时访问和更改都会更糟.有没有更好的方法来处理这个问题.我知道GameObject.Find方法对性能的影响有多严重......

c# optimization unity-game-engine

3
推荐指数
1
解决办法
776
查看次数

另一个游戏对象后面的粒子系统渲染

首先,我想让你了解我的英语。

我使用源代码手动将相机的投影更改为正交。请参考下面的代码。

using UnityEngine;
using System.Collections;

public class CameraOrthoController : MonoBehaviour
{
    private Matrix4x4 ortho;

    private Matrix4x4 perspective;

    public float near = 0.001f;

    public float far = 1000f;

    private float aspect;

    public static CameraOrthoController Instance
    {
        get
        {
            return instance;
        }
        set { }
    }

    //-----------------------------------------------------
    private static CameraOrthoController instance = null;
    //---------------------------------------------------
    // Use this for initialization
    void Awake()
    {
        if (instance)
        {
            DestroyImmediate(gameObject);
            return;
        }

        //  ? ????? ??? ?? ????? ???
        instance = this;
    }

    private void …
Run Code Online (Sandbox Code Playgroud)

c# unity-game-engine particle-system

3
推荐指数
1
解决办法
5718
查看次数

从 UnityWebGL jslib 返回字符串

我想使用 jslib 获取url 参数

像这样的代码

jslib

  GetUrl: function(){
  var s ="";
  var strUrl = window.location.search;
  var getSearch = strUrl.split("?");
  var getPara = getSearch[1].split("&");
  var v1 = getPara[0].split("=");
        alert(v1[1]);
   return v1[1];
  },
});
Run Code Online (Sandbox Code Playgroud)

C#

[DllImport("__Internal")]
public static extern string GetUrl();


void Start () {
    TextShow.text = GetUrl();
}
Run Code Online (Sandbox Code Playgroud)

当从 jslib 运行警报时,我看到警报中显示正确的字符串,但 UGUI 文本什么也没显示。

为什么会发生这种情况?

html javascript get unity-game-engine unity-webgl

3
推荐指数
1
解决办法
3480
查看次数