Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Let Scriptable Object update its data at runtime

Discussion in 'Scripting' started by CptBokkwurst, May 12, 2023.

  1. CptBokkwurst

    CptBokkwurst

    Joined:
    Apr 30, 2022
    Posts:
    2
    Hi folks,
    I'm new to Unity and programming in general and recently learned about scriptable objects. I tried to implement one to track the time of day inside my game, but I can't figure out how to update the time just by using methods inside the scriptable object. I could do that via a MonoBehaviour, but imo that would kinda conflict with the purpose of a scriptable object.

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. [CreateAssetMenu(fileName = "_World_", menuName = "ScriptableObjects/World")]
    7. public class _World_ : ScriptableObject
    8. {
    9.     // ---------------------------- time of day ------------------------------------
    10.  
    11.     private DateTime daytime;
    12.     [SerializeField] private bool updateDaytime;
    13.     [SerializeField] private string daytimestring;
    14.  
    15.     // --- private
    16.  
    17.     private void OnEnable()
    18.     {
    19.         Debug.Log("OnEnable");
    20.  
    21.         updateDaytime = true;
    22.         daytimestring = "";
    23.     }
    24.  
    25.     public IEnumerator NewDayTime()
    26.     {
    27.         Debug.Log("NewDayTime()");
    28.         if (updateDaytime)
    29.         {
    30.             daytime = DateTime.Now;
    31.             Debug.Log(daytime.ToString());
    32.             daytimestring = daytime.ToString();
    33.  
    34.             yield return new WaitForSeconds(1);
    35.             NewDayTime();
    36.         }
    37.     }
    In my approach the
    public IEnumerator NewDayTime()
    gets called from an MonoBehaviour, but it still just works once, and the method won't get called again.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    This doesn't make sense.

    Of course you can update anything from anything. That's how scripting works.

    MonoBehaviours and ScriptableObjects have completely different reasons for existing.