使用随机变量实例化可脚本化对象

时间:2021-06-01 17:18:33

标签: c# unity3d scriptable-object

我刚刚开始使用 scriptableobject,我正在尝试实例化/创建一个非常基本的 scriptableobject 的实例,它有 4 行数组。

我正在尝试实例化我创建的一个脚本对象,每次创建他都会随机化他的变量

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

[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
    [SerializeField]
    public string [] charName;
    public string [] charDescription;
    public string [] charSin;
    public Sprite [] charIcon;
}

我在检查器内部对一个可编写脚本的对象所做的更改,每次我创建新对象时,只会更改他的内部变量。有可能实现吗?

1 个答案:

答案 0 :(得分:0)

好的,所以我设法创建的东西可能不是正确的方法,但是在按下一个键(现在测试)之后,它使用我现在放置的随机图标实例化我的脚本对象。我将添加 3 个脚本,因为它仅用于测试,所以名称不好,(测试 - 它的脚本参考我的可脚本对象位于空游戏对象上,测试 2 - 它的脚本位于我使用可脚本对象实例化的预制件上)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class testing2 : MonoBehaviour
{
    //public ScriptableObject person;
    public CharStats charSats;

    public Sprite sprite2;
    private SpriteRenderer spriteRender;
    private void Start()
    {
        spriteRender = GetComponent<SpriteRenderer>();
        GetRandomSprite();

    }

    public Sprite GetRandomSprite()
    {
        int randomIndex = Random.Range(0, charSats.charIcon.Length);

        
        Debug.Log(charSats.charIcon[randomIndex]);

        if (sprite2 == null)
        {
            sprite2 = charSats.charIcon[randomIndex];
            spriteRender.sprite = sprite2;

        }
        return charSats.charIcon[randomIndex];
        
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class Testing : MonoBehaviour
{
    public GameObject Player;

    private void Update()
    {
        SpawnPlayer();
    }

    public void SpawnPlayer()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            GameObject spawnPalyer = Instantiate(Player, new Vector3(Random.Range(-10,10), Random.Range(-10, 10)), Quaternion.identity) as GameObject;
        }

    }


}

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

[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
    [SerializeField]
    public string [] charName;
    public string [] charDescription;
    public string [] charSin;
    public Sprite [] charIcon;

    
}