通过商店更改玩家精灵

时间:2018-08-16 07:08:56

标签: c# unity3d

我正在尝试创建一家商店,您可以在其中购买游戏内货币以外的其他玩家精灵。 (商店是与关卡不同的场景),有人告诉我使用scriptableobject是可行的方法,所以我做了以下事情:

[CreateAssetMenu(fileName = "New Sprite", menuName = "Player Sprites")]
public class PlayerSprites : ScriptableObject
{
    public string spriteName;
    public int cost;
    public Sprite sprite;
}

我刚刚添加了播放器脚本

public SpriteRenderer spriteRenderer;

void Start()
{
    spriteRenderer = GetComponent<SpriteRenderer>();
}

我不太确定该从何而去...如何在按下Sprite按钮时将Sprite从其他场景渲染到播放器上...非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尽管您的问题很朦胧,但我真的看不到您到目前为止所做的尝试:

现在,您将需要一个ScriptableObject用于每个 Sprite项目……我认为这不是您想要的。您宁愿使用一个ScriptableObject存储所有 Sprite项的信息。

using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "Assets/New Store", menuName = "Sprites-Store")]
public class SpriteStoreContainer : ScriptableObject
{
    public List<StoreSpriteItem> SpriteItems = new List<StoreSpriteItem>();

    // you can/should also implement methods here as in any usual component!
}

还要确保您的fileNameAssets/开头

还有一个单独的类别,用于使用[System.Serializable]的商品,因此您可以在检查器中显示它。

using UnityEngine;

[System.Serializable]
public class StoreSpriteItem
{
    public string spriteName;
    public int cost;
    public Sprite sprite;
    public bool IsAvailable;

    // also here you could/should implement some methods e.g.
    public void BuyItem()
    {
        IsAvailable = true;
    }
}

然后回到Unity:

  1. 现在您首先需要Instantiate ScriptableObject资产:
    转到项目视图(资产)-> 右键单击->在菜单中单击创建->单击 Sprites-Store < br /> enter image description here 这应在New Store下创建一个名为Assets(。asset)的新资产
    enter image description here

  2. 现在在此创建的资产的检查器中,填写所需的信息。您应该看到带有SpriteItems的列表Size = 0
    enter image description here
    要创建元素,只需增加Size的值,然后按Enter键(注意:Unity不会询问您是否更改了此值=>请注意不要通过稍后意外减小该值来删除项目) 现在,您可以调整这些SpriteItems的所有信息
    enter image description here

  3. 以后,无论何时需要访问此资产的信息,您都可以将引用用作其他任何组件=>,例如,可以为其分配引用。通过检查员使用公共字段,例如

    using UnityEngine;
    
    public class ScriptThatUsesStore : MonoBehaviour
    {
    
        public SpriteStoreContainer Store;
    
        public void DoSomthingWithStore()
        {
            // example: just get the first List element
            Sprite someSprite = Store.SpriteItems[0].sprite;
        }
    }
    

    enter image description here
    然后访问其中的数据。尽管我强烈建议您宁愿在ScriptableObject中实现某些方法,例如BuyItemGetSprite等。

相关问题