- Home /
How to use a local var in the script
I have this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinSpawn : Coincollecting
{
public GameObject Coin;
float randX;
float randY;
Vector2 Spawn;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
void Start()
{
}
public void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
randX = Random.Range(-15.16f, 15.16f);
randY = Random.Range(-6.82f, 6.82f);
Spawn = new Vector2(randX, randY);
var KreisKaputt = Instantiate(Coin, Spawn, Quaternion.identity);
Destroy(KreisKaputt, 5f);
}
if (treffen == true)
{
Destroy(KreisKaputt);
}
}
}
Problem: I cant use KreisKaputt in if (treffen == true) Any ideas :(
Answer by Weaver13 · Jul 23, 2020 at 05:45 AM
To add to DaDonik's answer, you may not want to use "var" at all.
kreisKapputt = GameObject.Instantiate(Coin, Spawn, Quaternion.identity);
Then at the start of your mono script put:
public GameObject kreisKapputt;
Whenever accessing it, be sure to check if it is null first!
Answer by DaDonik · Jul 22, 2020 at 03:15 PM
Variables are only valid in the scope that they are defined in. A scope is a section of code surrounded by { }. So the solution to your problem is to move "var KreisKaputt" to another scope, preferably the one of the Update() method itself. Just initialize it with null.
Your answer
![](https://koobas.hobune.stream/wayback/20220613003751im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Make Animator bool false when object is destroyed 0 Answers
2d Endless Runner: Deleting objects behind player and platform limit 2 Answers
Is Destroy(transform.parent.gameObject) Unreliable? 1 Answer
IF statement ignoring condition 2 Answers