-1

I am using Vector3.MoveTowards, i have a separate function that instantiates a gameObject and I want to move this, In the Update function i have an if statement,

void Update()
   {
       if (move == true)
       {
           
          
           DrewCard.transform.position = Vector3.MoveTowards(DrewCard.transform.position, pos + new Vector3((CardsInHand.Count - 1) * width + (width / 2), -63, 1), change);
       }

But this does not work as "DrewCard" is not defined, when i define it using GameObject DrewCard; It then says "NullReferenceException: Object reference not set to an instance of an object" Any ideas?

TheBlueToo
  • 31
  • 4

1 Answers1

0

I might be assuming a bit now as shared code is not showing whole picture, but to you surely need to have DrewCard defined outside of this function somewhere inside this class of yours. I would be assuming it would be of type GameObject. Then as you mentioned you're instantiating that in some other function, you need to use return value (which is the gameobject you're looking for) and store it as DrewCard.

Also make sure to verify in your update function that DrewCard is not null. So overall script may look like this:

public class MyClass : MonoBehaviour {
    // Your DrewCard object
    private GameObject DrewCard;

    // Reference to card prefab assignable in Editor thanks to SerializeField
    [SerializeField] private GameObject CardPrefab;


    private void Start() {
        DrewCard = Instantiate(CardPrefab, Vector3.zero, Quaternion.identity);
    }

    private void Update() {
        if(DrewCard != null) {
            // Do the movement magic
        }
    }
}

Hope this covers your question, let me know if now

R1cky
  • 662
  • 5
  • 16
  • When the game object is instantiated, CardPrefab for me is a randomly picked gameObject which determines what card you draw, so how would I do this keeping this in mind? – TheBlueToo Jan 04 '22 at 20:39
  • basic logic is that first you need to define what to instantiate and only then instantiate it. Once it is instantiated, you can store the reference to this DrewCard Obvious problem may occur if you Instantate some card and that object has some internal logic that will "change" itself by e.g destroying itself and replacing self with different card - that will be an issue, because reference stored in DrewCard will not be valid anymore – R1cky Jan 04 '22 at 20:48
  • In case you need to have some card swapping logic AFTER the card has bee instantiated and still need reference to it, you can use some wrapper object that will not be destroyed, containing this swapping logic without any visuals and only replacing it's content – R1cky Jan 04 '22 at 20:51