Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by goldendonut · Dec 24, 2021 at 06:15 AM · scriptableobjectdotscraftingmachine

ECS working with scriptable objects for crafting

I am currently trying to create a factory game, but can't figure out how to do recipes/crafting using ECS.

I would like machines that are entities, to have an inventory of sorts and check if it has the required items from the recipe. currently, all I need is the recipe data, the rest I should be able to do.

I have tried to get scriptable objects(my preferred way) but couldn't figure it out. is there any way to get this to work?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by andrew-lukasik · Dec 26, 2021 at 02:10 AM


PROBLEM: ScriptableObjects, being a managed type, are not accessible from ecs components

SOLUTION: Create BlobAssetReference<T> (read-only memory block) based on given ScriptableObject and read that.


scriptable object:

transmutation recipe scriptableObject

gameObject:

transmuter gameObject

system running:

transmuter system running

TransmutationRecipeAsset.cs

 using System.Collections.Generic;
 using Unity.Entities;
 using Unity.Collections;
 using UnityEngine;
 
 [CreateAssetMenu( menuName="Game/Recipe Asset" , fileName="recipe for 0" , order=1 )]
 public class TransmutationRecipeAsset : ScriptableObject
 {
     static Dictionary<string,BlobAssetReference<RecipeBlobAsset>> Allocations = new Dictionary<string,BlobAssetReference<RecipeBlobAsset>>();
     [SerializeField] Substance _product;
     [SerializeField][Min(1)] int _batchProducts = 1;
     [SerializeField][Min(0.1f)] float _batchDuration = 1.5f;
     [SerializeField] InventoryItem[] _ingredients;
     public BlobAssetReference<RecipeBlobAsset> ToBlobAssetReference ()
     {
         if( Allocations.ContainsKey(this.name) )
         {
             return Allocations[this.name];
         }
         else
         {
             BlobAssetReference<RecipeBlobAsset> recipe;
             {
                 var builder = new BlobBuilder( Allocator.Temp );
                 ref var root = ref builder.ConstructRoot<RecipeBlobAsset>();
                 {
                     root.Product = _product;
                 }
                 {
                     root.BatchProducts = _batchProducts;
                 }
                 {
                     root.BatchDuration = _batchDuration;
                 }
                 {
                     int numIngredients = _ingredients.Length;
                     var arr = builder.Allocate( ref root.Ingredients , numIngredients );
                     for( int i=0 ; i<numIngredients ; i++ ) arr[i] = _ingredients[i];
                 }
                 recipe = builder.CreateBlobAssetReference<RecipeBlobAsset>( Allocator.Persistent );
                 builder.Dispose();
             }
 
             Allocations.Add( this.name , recipe );
 
             return recipe;
         }
     }
 }
 
 public struct RecipeBlobAsset
 {
     public Substance Product;
     public int BatchProducts;
     public float BatchDuration;
     public BlobArray<InventoryItem> Ingredients;
 }
 
 public enum Substance : byte { Lead , Mercury , Gold }

TransmuterComponent.cs

 using Unity.Entities;
 using UnityEngine;
 
 [DisallowMultipleComponent]
 [RequireComponent( typeof(InventoryComponent) )]
 public class TransmuterComponent : MonoBehaviour, IConvertGameObjectToEntity
 {
     [SerializeField] TransmutationRecipeAsset _recipeAsset;
     public void Convert ( Entity entity , EntityManager dstManager , GameObjectConversionSystem conversionSystem )
     {
         dstManager.AddComponentData( entity , new Transmuter{
             RecipeData        = _recipeAsset.ToBlobAssetReference()
         } );
     }
 }
 
 public struct Transmuter : IComponentData
 {
     public BlobAssetReference<RecipeBlobAsset> RecipeData;
     public bool BatchStarted;
     public float BatchTime;
 }

InventoryComponent.cs

 using Unity.Entities;
 using UnityEngine;
 
 [DisallowMultipleComponent]
 public class InventoryComponent : MonoBehaviour, IConvertGameObjectToEntity
 {
     [SerializeField] InventoryItem[] _items;
     public void Convert ( Entity entity , EntityManager dstManager , GameObjectConversionSystem conversionSystem )
     {
         var inventory = dstManager.AddBuffer<InventoryItem>( entity );
         for( int i=0 ; i<_items.Length ; i++ )
             inventory.Add( _items[i] );
     }
 }
 
 [InternalBufferCapacity( 3 )]
 [System.Serializable]
 public struct InventoryItem : IBufferElementData
 {
     public Substance Type;
     public int Quantity;
 }

TransmutationSystem.cs

 using Unity.Entities;
 using Unity.Jobs;
 
 [UpdateInGroup( typeof(SimulationSystemGroup) )]
 public class TransmutationSystem : SystemBase
 {
     protected override void OnUpdate ()
     {
         float deltaTime = Time.DeltaTime;
 
         Entities
             .WithName("transmutation_job")
             .ForEach( ( ref Transmuter transmuter , ref DynamicBuffer<InventoryItem> inventory ) =>
             {
                 ref var recipe = ref transmuter.RecipeData.Value;
 
                 if( transmuter.BatchStarted )
                 {
                     transmuter.BatchTime += deltaTime;
                     if( transmuter.BatchTime>recipe.BatchDuration )
                     {
                         transmuter.BatchTime -= recipe.BatchDuration;
                         transmuter.BatchStarted = false;
 
                         bool itemCreated = false;
                         for( int i=0 ; i<inventory.Length ; i++ )
                         {
                             var item = inventory[i];
                             if( item.Type==recipe.Product )
                             {
                                 item.Quantity += recipe.BatchProducts;
                                 inventory[i] = item;
                                 itemCreated = true;
                                 break;
                             }
                         }
                         if( !itemCreated )
                         {
                             inventory.Add( new InventoryItem{
                                 Type        = recipe.Product ,
                                 Quantity    = recipe.BatchProducts
                             } );
                         }
                     }
                 }
                 else
                 {
                     int numPassed = 0;
                     for( int i=0 ; i<recipe.Ingredients.Length ; i++ )
                     {
                         var ingredient = recipe.Ingredients[i];
                         bool passed = false;
                         foreach( var item in inventory )
                         {
                             if( item.Type==ingredient.Type && item.Quantity>=ingredient.Quantity )
                             {
                                 passed = true;
                                 numPassed++;
                                 break;
                             }
                         }
                         if( !passed ) break;
                     }
                     if( numPassed==recipe.Ingredients.Length )
                     {
                         for( int i=0 ; i<recipe.Ingredients.Length ; i++ )
                         {
                             var ingredient = recipe.Ingredients[i];
                             for( int k=0 ; k<inventory.Length ; k++ )
                             {
                                 var item = inventory[k];
                                 if( item.Type==ingredient.Type )
                                 {
                                     item.Quantity -= ingredient.Quantity;
                                     inventory[k] = item;
                                 }
                             }
                         }
 
                         transmuter.BatchStarted = true;
                     }
                 }
             } )
             .WithBurst().ScheduleParallel();
     }
 }


screenshot-2021-12-26-030453.jpg (50.3 kB)
screenshot-2021-12-26-030517.jpg (28.4 kB)
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image goldendonut · Dec 26, 2021 at 07:33 AM 0
Share

Thank you so much! this is has given me the motivation to complete this game.

avatar image andrew-lukasik goldendonut · Dec 26, 2021 at 09:15 PM 0
Share

Take it easy mate, Rome Factorio wasn't built in a day :T

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

136 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

EntityArchetype and ScriptableObject 0 Answers

Modifyable item system vs ScriptableObject 0 Answers

Unity recompilation time slowly increases each time it's recompiled. Why? 0 Answers

Make a folder that acts same as streamingassets but can use and edit .asset types. 0 Answers

How come my scriptable object only receives new information when it's selected in the inspector? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges