I have been programming a script to make the movement of an object when it is touched by a player and that when it stops touching it it stops moving. But I have this error.
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LogicaCaja : MonoBehaviour
{
public float speed;
public float maxSpeed;
public bool istouching;
private Rigidbody2D rb2d;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Player" && istouching = true)
{
rb2d.AddForce(Vector2.right * speed);
}
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
void OnCollisionExit2D(Collision2D col)
{
if (col.gameObject.tag == "Player")
{
istouching = false;
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y);
}
}
}
You can simply use code-tags when posting code (no need to post plain-text or images of code or both). You can also go back and just edit your first post too to include them.
If you are reporting an error, report it in full including the line/column number reported with it and if it’s not identical to the code you’re posting then indicate which line it is.
You can also look up the error with Google which is easy to do. To be honest, the error is pretty self explanatory. You need to assign whatever it is you’re assigning to what it says, a variable, property or indexer. It might be that on the line/column is actually gives you, you didn’t mean to assign anything which I think is the case here.
I can see you typed “istouching = true” but presume you mean to use “==”.
Hello again, thanks for helping me. If I use the comparer “==” it gives another error.
This is the new error:
Assets\Scripts\LogicaCaja.cs(45,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
This is the error exactly if i dont use “==”: Assets\Scripts\LogicaCaja.cs(25,12): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
Hold on, this is a different line? On that line you want to assign the value true not check the value if it’s true. Nobody said to change that line. I was referring to line 25.
Is this your code? Are you just guessing at what this code does? I’m confused.
This is why you should always report the full error including the line/column numbers.
I just have one more question, why when I start the game does the box slide little by little? Everything works fine except that. In the script I set the speed at the beginning to be 0.