- Home /
How do I make Vector2 X and Y values into a float? C#
How do I make Vector2 X and Y values into a variable in C#?
I have looked on the web including the scripting reference for about 2 hours (I'm new) and have found nothing.
I just want to figure out how to extract the X and Y values from a vector 2 and make them into a variable. I would be very grateful if you answered my question with a block of code in C#.
I don't know how to get the X value from a vector3 either, but I'm assuming they are almost identical for these purposes.
Not sure where your problem is, but given a Vector3 like transform.position, you can do:
float x = transform.position.x;
If this is your issue, I recommend reviewing a C# book. It will explain how to variables in classes and structures.
Hmmm i understand my question is a bit confusing.
Let me put down what I am trying to ask in conext. I am currently saving my mouseclick transform into my mouse2 vector2.
using UnityEngine; using System.Collections;
public class $$anonymous$$ove : $$anonymous$$onoBehaviour {
public Vector2 mouse2;
void Update()
{
mouse2 = Input.mousePosition;
}
}
I want to be able to then take the X value of mouse2 and the Y value of mouse2 out of it and make it into specific floats so I can use them for other purposes.
I don't think that works, I tried it in my script and it stopped it from working. Should I not be putting it under the line that has my mouse2 vector2?
to turn any value into a float its as simple as multiplying the number by 1.0
int number = 25;
float numbertofloat = number * 1.0f;
not necessarily an answer to your question, but a useful tip either way
Answer by Joseph Lerner · Jul 28, 2014 at 04:28 AM
Got it!
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public Vector2 mouse2;
public float x;
void Update()
{
mouse2 = Input.mousePosition;
x = mouse2.x;
}
}
As you can see, I first had to make a new public float next to my new vector2, and then under the void update I made the floats value = the value of X in mouse2. Thanks for that last post.
Answer by Nition · Jul 28, 2014 at 02:45 AM
Robertbu's comment is correct. This will work:
using UnityEngine;
public class Move : MonoBehaviour {
Vector2 mouse2;
void Update() {
mouse2 = Input.mousePosition;
float mouseX = mouse2.x;
float mouseY = mouse2.y;
print("Mouse X is: " + mouseX + " Mouse Y is: " + mouseY);
}
}
If that doesn't work, then something is wrong somewhere else. You could tell us what error you're getting.
Your answer
Follow this Question
Related Questions
Errors in Vector2 variables 1 Answer
Declaring a type in JavaScript arrays 3 Answers
Need to increase the gameobject value . 2 Answers
Vector2.Angle questions and confusion. 1 Answer
Vector2 is always (0,0) - HELP 1 Answer