access object from another
hello all ! I'm a begginer and I learn Unity with a book that gave us that code :
using UnityEngine;
using System.Collections;
public class PlayerStats : MonoBehaviour {
public int health = 6;
public int coinsCollected = 0;
public void CollectedCoin(int coinValue){
this.coinsCollected = this.coinsCollected += coinValue;
}
}
and in the coin script :
using UnityEngine;
using System.Collections;
public class CoinPickUp : MonoBehaviour {
public int coinValue = 1;
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.tag == "Player"){
PlayerStats stats = collider.gameObject.GetComponents<PlayerStats>();
stats.CollectedCoin(this.coinValue);
Destroy(this.gameObject);
}
}
}
and here's the log error :
Assets/_scripts/CoinPickUp.cs(14,37): error CS0029: Cannot implicitly convert type `PlayerStats[]' to `PlayerStats'
Please someone know how to resolve this ?
Thank you very much !
Answer by haiderInUnity · Jan 31, 2016 at 11:44 AM
The error is in line 14
PlayerStats stats = collider.gameObject.GetComponents<PlayerStats>();
here It should be GetComponent rather than GetComponents. Getcomponents needs a return type of array to store all components found even if it is one and thus the error.
Answer by dj b.one · Jan 31, 2016 at 11:57 AM
oh damn so simple ! thank you very much haiderInUnity ;)
Your answer
Follow this Question
Related Questions
How do I run an animation then destroy a game object? 1 Answer
How can i change bool of other gameobject? 1 Answer
I need quick help with my C# code GetComponent! 1 Answer
this.GetComponent() won't return gameObject? How to get it without using this.gameObject? 3 Answers
Reference a script on a gameobject that is disabled in scene 0 Answers