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
0
Question by Spoopy_ · Mar 29 at 04:33 AM · scriptingbasicsscriptable objectmodular

Help with modular projectile system

Hello,


I'm having trouble with a modular projectile system. Currently I have it so a Spawner has a function that fires projectiles, taking in the Projectile type, the pattern to fire them in and the origin transform. Currently im trying to add a sort of modifier system, where i can add unique effects once the projectile decays, hits something etc etc.


I've managed to create an on death effect:

 public class Modifier : ScriptableObject, IModifier
 {
     public void OnDecay(Transform transform)
     {
         Debug.Log("ondecay");
         var spawner = Instantiate(GameAssets.I.spawner);
         spawner.transform.position = transform.position;
         spawner.GetComponent<Spawner>().ShootPattern(spawner.transform, GameAssets.I.grenade, GameAssets.I.flower, default, true);
     }
 }


My problem now however, is I'm unsure how to be able to create another modifier, that can be swapped in and out whenever i want.

Currently, the default OnDecay effect spawns 8 more projectiles in a flower shape, but for example, if i wanted it to explode or something, im unsure how i would be able to create another modifier that i can change the effect of, whilst still being able to input it into the same fields as the previous one.


Im going to keep at it, if i find a solution ill post it here, any help is appreciated, Thanks.


Comment
Add comment · Show 2
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 andrew-lukasik · Mar 29 at 10:10 AM 0
Share

You can pass the modifiers to the spawner

 public class Modifier : ScriptableObject, IModifier
 {
     [SerializeField] IModifier[] _onDecay = null;
     public void OnDecay ( Transform transform )
     {
         Spawner spawner = Instantiate( GameAssets.I.spawner ).GetComponent<Spawner>();
         spawner.transform.position = transform.position;
         
         foreach( IModifier next in _onDecay )
             spawner.AddOnDecayModifier( next );
         spawner.ShootPattern( spawner.transform , GameAssets.I.grenade , GameAssets.I.flower , default , true );
     }
 }
avatar image andrew-lukasik · Mar 29 at 10:21 AM 0
Share

The problem is that interface fields, such as IModifier aren't serializable, so those wont show up in the inspector.

To fix this, here is a basic example of how to create events as ScriptableObjects that are interchangeable, easy to create/edit and will show up in the inspector:

PointEvent.cs:

 using UnityEngine;
 /// abstract base class, think of it as a (serializable) interface
 public abstract class PointEvent : ScriptableObject
 {
     public abstract void Execute ( Vector3 point );
 }


SpawnAtPointEvent.cs:

 using UnityEngine;
 /// event  example & it's implementation
 [CreateAssetMenu( fileName="spawn at point 0" , menuName="Game/Scriptable Events/Spawn At Point" , order=1 )]
 public class SpawnAtPointEvent : PointEvent
 {
     [SerializeField] GameObject _prefab = null;
     public override void Execute ( Vector3 point )
     {
         var instance = Instantiate( _prefab , point , Quaternion.identity );
     }
 }


TriggerSpawnerAtPointEvent.cs:

 using UnityEngine;
 
 [CreateAssetMenu( fileName="trigger spawner at point 0" , menuName="Game/Scriptable Events/Trigger Spawner At Point" , order=1 )]
 public class TriggerSpawnerAtPointEvent : PointEvent
 {
     [SerializeField] PointEvent[] _onDecay = null;
     public override void Execute ( Vector3 point )
     {
         Spawner spawner = Instantiate( GameAssets.I.spawner ).GetComponent<Spawner>();
         spawner.transform.position = point;
         
         foreach( var next in _onDecay )
             spawner.AddOnDecayModifier( next );
         spawner.ShootPattern( spawner.transform , GameAssets.I.grenade , GameAssets.I.flower , default , true );
     }
 }


ScriptableEventTester.cs:

 using UnityEngine;
 public class ScriptableEventTester : MonoBehaviour
 {
     /// this field will accept any scriptable object that inherits from PointEvent:
     [SerializeField] PointEvent[] _pointEvents = new PointEvent[0];
     void OnEnable ()
     {
         Vector3 pos = transform.position;
         foreach( var next in _pointEvents )
             next?.Execute( pos );
     }
 }

1 Reply

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

Answer by Spoopy_ · Mar 29 at 12:29 PM

Hello sorry! I've managed to figure out my own solution before i saw your comments @andrew-lukasik . I've changed the modifiers to be MonoBehaviours. So i've got my base Modifier class

 public class Modifier : MonoBehaviour, IModifier
 {
     public virtual void OnDecay(Transform transform)
     {
         Debug.Log("default");
     }
 }

Which just contains the default on decay method now, and instead i've opted to create seperate scripts that derive from modifier. I've got a list of those scripts in string form within my GameAssets script. Now, whenever i call the ShootPattern method, it takes a string in place of a modifier. It then uses this string to parse through the list in GameAssets to find if its a valid script and add the component to the bullet itself, whilst also giving the bullet a reference to the component. bullet calls that component on death etc etc. Component gets deleted along with bullet afterwards.

Heres the updated sections of the Spawner script

 public void ShootPattern(Transform origin, Projectile projectile, ProjectilePattern pattern, string mod = null, bool temp = false)
     {
         //randomize the pattern if it needs to be
         if (pattern.random)
         {
             for (int i = 0; i < pattern.projCount; i++)
             {
                 pattern.projDir[i] = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
                 Debug.Log("Randomized dir - " + pattern.projDir[i]);
                 pattern.projAngle[i] = Random.Range(0f, 1f);
                 Debug.Log(pattern.projAngle[i]);
                 
             }
         }
         StartCoroutine(Shoot(pattern, projectile, origin, mod, temp));
         
     }
 
     IEnumerator Shoot(ProjectilePattern pattern, Projectile projectile,  Transform origin, string mod, bool temp)
     {
         for (int i = 0; i < pattern.projCount; i++)
         {
             //Wait for the delay time.
             yield return new WaitForSeconds(pattern.projTimes[i]);
             
             //instantiate new projectile and grab reference to it.
             var proj = Instantiate(projectilePrefab);
             
             //If the modifier name is valid, Add the modifier to the bullet, else add the default modifier.
             if (GameAssets.I.modifiers.Contains(mod))
             {
                 Debug.Log("mod " + mod);
                 proj.gameObject.AddComponent(Type.GetType(mod));
                 proj.GetComponent<ProjectileObject>().modifier = (Modifier)proj.GetComponent(Type.GetType(mod));
             }
             else
             {
                 Debug.Log("Default mod");
                 proj.gameObject.AddComponent<Modifier>();
             }
             
             //setting the movement direction of the bullet
             var forward = origin.forward;
             Vector3 direction = new Vector3(forward.x + pattern.projDir[i].x, forward.y + pattern.projAngle[i], forward.z + pattern.projDir[i].y - 1);
             proj.transform.position = origin.position + direction.normalized;
             Debug.Log("direction = " + direction.normalized);
             proj.GetComponent<ProjectileObject>().velocity = direction.normalized;
             proj.GetComponent<ProjectileObject>().currentProjectile = projectile;
         }
 
         if (temp)
         {
             Destroy(gameObject);
         }
     }


Its a bit roundabout but i'm quite happy with it overall. Thanks for your help anyways.

Comment
Add comment · 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

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

141 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 avatar image avatar image avatar image avatar image avatar image

Related Questions

Add an effect animation to main character? 1 Answer

he type or namespace name `Image' could not be found 1 Answer

How would i make an object change color every second? 0 Answers

My GameObject (c#) haven't sprite defined 4 Answers

New to Raycasts, trouble using "hit" 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