Thanks you for the documentation !
Well, it seems like the AddComponent<>() method is working, but I realized that create a reference to this class isn’t the thing I need, because my “PlayerInput” class contains an “FixedUpdate()” method to manage the player’s movements.
My “PickUpEvent” class is calling the “FixedUpdate” method for its own GameObject ( the fruits ), so it throws an huge amount of errors ( since the fruits don’t have any RigidBody ).
The thing that I want to do is :
When a fruit is eaten by the player ( when the player trigger the Collider of the fruit ) it calls the OnTriggerEnter() in the “PickUpEvent” class, which also calls the “SpawnExtension()” method in the “PlayerInput” class.
I could use static methods, but I just realized that I can get the player’s collider when it trigger the fruit’s collider … so maybe I can call the SpawnExtension() method from this, right ?
There is my script :
- PlayerInput class
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
//speed to modify
public float speed;
//contain the player extension prefab
public GameObject playerExtensionPrefab;
//rigidbody of the playerhead
private Rigidbody playerRb;
//contains old direction
private Vector3 oldMovement;
//contains applied movement
private Vector3 movement;
//contains every player extension prefab
private List<GameObject> bodyParts;
void Start()
{
playerRb = GetComponent<Rigidbody>();
bodyParts = new List<GameObject>();
oldMovement = new Vector3(1.0f, 0, 0);
playerRb.AddForce(oldMovement*speed);
}
void FixedUpdate()
{
Movement();
}
void Movement ()
{
//..
}
void ReverseRotation90 ()
{
//..
}
void Rotation90 ()
{
//..
}
void StopPlayerMovement()
{
//...
}
string DirectionFaced()
{
//..
}
public void SpawnExtension ()
{
if (bodyParts.Count != 0)
{
bodyParts.Add(
Instantiate(playerExtensionPrefab,
new Vector3(bodyParts[bodyParts.Count-1].transform.position.x - 1.0f, transform.position.y, transform.position.z),
Quaternion.identity,
transform) as GameObject);
}
else
{
bodyParts.Add(
Instantiate(playerExtensionPrefab,
new Vector3(transform.position.x - 1.0f, transform.position.y, transform.position.z),
Quaternion.identity,
transform) as GameObject);
}
}
}
- PickUpEvent
using UnityEngine;
public class PickUpEvent : MonoBehaviour {
PlayerInput playerInputSession;
private void Awake()
{
playerInputSession = gameObject.AddComponent<PlayerInput>();
}
void OnTriggerEnter()
{
Destroy(gameObject);
playerInputSession.SpawnExtension();
}
}