I tried following along with this lecture by applying it to the 2D Laser Defender game from the 2D course. I loved the interface idea because my weapon scripts for Laser Defender were SUPER messy.
I ran into a problem with serializing the interface, as Sam and Rick do in the video (at 3:32). In my Player.cs script, I wrote:
[SerializeField] IWeapon activeWeapon = null;
(I changed it from IGun to reflect the game I was making.)
I made an IWeapon interface:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
interface IWeapon
{
void Fire();
}
I then created RapidFire.cs and implemented the interface:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RapidFire : MonoBehaviour, IWeapon
{
[SerializeField] GameObject projectile;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileFiringPeriod = 0.1f;
[SerializeField] AudioClip projectileSound;
[SerializeField] [Range(0, 1)] float projectileSoundVolume = .25f;
public void Fire()
{
StartCoroutine(FireContinuously());
}
IEnumerator FireContinuously()
{
while (true)
{
AudioSource.PlayClipAtPoint(projectileSound,
Camera.main.transform.position,
projectileSoundVolume);
GameObject newProjectile = Instantiate(
projectile,
transform.position,
Quaternion.identity) as GameObject;
newProjectile.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
yield return new WaitForSeconds(projectileFiringPeriod);
}
}
}
Finally, I created a gameobject that has the RapidFire (IWeapon) script on it.
The problem comes in when I attempt to drag the prefabbed RapidFire gameobject onto the serialized IWeapon field (like Sam and Rick do in the video). The serialized field does not show up. Initial searching on Unity forums seems to indicate Unity does not support serialization of interfaces.
How did Sam and Rick pull it off? Am I missing something?