Last active
June 26, 2020 21:09
-
-
Save James-Frowen/32e0aa58010e06a03d79ccdda4d9ce27 to your computer and use it in GitHub Desktop.
Unity3d ScriptableObject Reference Example, concept from https://youtu.be/raQ3iHhE_Kk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
GameObject A would have PlayerControler and SetPlayerReference. | |
GameObject B would have WantsToUsePlayer. | |
SetPlayerReference and WantsToUsePlayer have same PlayerReference set via the inspector. | |
WantsToUsePlayer will be able to use PlayerReference to have reference to PlayerControler. Even if GameObject A is spawned from a prefab after the game starts. | |
*/ | |
[CreateAssetMenu()] | |
public class PlayerReference : ScriptableObject | |
{ | |
public PlayerControler player; | |
} | |
[RequireComponent(typeof(PlayerControler))] | |
public class SetPlayerReference : MonoBehaviour | |
{ | |
public PlayerReference reference; | |
public void OnEnable() | |
{ | |
reference.player = GetComponent<PlayerControler>(); | |
} | |
} | |
public class PlayerControler : MonoBehaviour | |
{ | |
public float health; | |
} | |
public class WantsToUsePlayer : MonoBehaviour | |
{ | |
public PlayerReference playerReference; | |
public void Update() | |
{ | |
var health = playerReference.player.health; | |
// does something with health | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment