- Home /
"This" not available in the current context
Why?
using UnityEngine;
using System.Collections;
public class HillScript1 : MonoBehaviour
{
bool direcright = true;
public float speed = 5.0f;
public float leftpoi = this.transform.position.x - 4;
public float rightpoi = this.transform.position.x;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (direcright)
{//x<1.4, x>4
GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, 0);
if (transform.position.x <= leftpoi)
{
direcright = false;
}
}
else {
GetComponent<Rigidbody2D>().velocity = new Vector2(speed, 0);
if (transform.position.x >= rightpoi)
{
direcright = true;
}
}
}
}
Comment
Best Answer
Answer by Fredex8 · Apr 09, 2016 at 06:47 PM
You cannot declare things outside of a function like that. Simple things like a boolean or public float speed = 5.0f;
are fine but when you start using references, getting positions and using math operators it isn't going to work.
Change it to this:
public float leftpoi;
public float rightpoi;
void Start()
{
leftpoi = gameObject.transform.position.x - 4;
rightpoi = gameObject.transform.position.x;
}
You can remove 'this' entirely or leave it in if you want. this.gameObject
is the same as gameObject
though. You can remove the gameObject too but personally I like to leave it in for clarity in case you are also using the transform from another object.
Your answer
![](https://koobas.hobune.stream/wayback/20220612074510im_/https://answers.unity.com/themes/thub/images/avi.jpg)