Содержание
- error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′
- 2 Ответов
- Ваш Ответ
- Welcome to Unity Answers
- Подписаться на вопрос
error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′
using UnityEngine; using System.Collections; using FSM;
> i created a fsm context that gets the transform and sets it as the direction. what i am trying to do get my character to move on its own the error i am having is converting it. also i am not sure if the way i am doing it will work. t$$anonymous$$s is in my context——
public Transform gettransform() < return Controller.transform; >public void setcontroller(Transform pos) < pos = Controller.transform;
>
2 Ответов
Ответ от Julien-Lynge · 08/03/12 22:17
I’m sorry, I couldn’t read your code (you didn’t format it nicely). However, just glancing at it, your problem is that a Transform is not a Vector3. A transform is all the position, rotation, scaling, etc. information for an object. Instead of using Vector3 whatever = transform;, you likely need to use Vector3 whatever = transform.position;
transform.position is the position of the object, and is a Vector3. Likewise, transform.scale is a Vector3, and transform.rotation is a quaternion.
Ответ от mpavlinsky · 08/03/12 22:20
I don’t know anyt$$anonymous$$ng at all about FSM but it seems like you should be doing
Ваш Ответ
Welcome to Unity Answers
If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.
Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.
Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.
Подписаться на вопрос
Ответы Ответы и комментарии
6 пользователей подписаны.
Источник
какая то ошибка |
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
|
|
Question:
Unity doesn’t seem to like the way I’m declaring my variables, I was just trying to clean up my code and moved some of the variables and now it doesn’t work.
The Error:
AssetsMovement.cs(33,22): error CS0029: Cannot implicitly convert type ‘UnityEngine.Vector3’ to ‘float’
AssetsMovement.cs(39,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’
AssetsMovement.cs(41,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’
AssetsMovement.cs(43,29): error CS1503: Argument 1: cannot convert from ‘float’ to ‘UnityEngine.Vector3’
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Movement : MonoBehaviour{
public CharacterController controller;
public Transform Player;
public Transform groundCheck;
public Text StaminaBar;
public LayerMask groundMask;
Vector3 move;
Vector3 velocity;
float WalkingSpeed = 12;
float SprintingSpeed = 15;
float CrouchingSpeed = 6;
float gravity = 30;
void Update(){
Speed();
Jump();
Crouching();
//Gravity
controller.Move(velocity * Time.deltaTime);
}
void Speed(){
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
float CurrentX = Player.transform.position.x;
float CurrentZ = Player.transform.position.z;
float move = transform.right * x + transform.forward * z;
bool isWalking = Input.GetKey(KeyCode.W);
bool isCrouching = Input.GetKey(KeyCode.LeftShift);
bool isSprinting = Input.GetKey(KeyCode.R);
velocity.y += gravity * Time.deltaTime;
if (isWalking){
controller.Move(move * WalkingSpeed * Time.deltaTime);
} else if (isCrouching){
controller.Move(move * CrouchingSpeed * Time.deltaTime);
}else if(isSprinting){
controller.Move(move * SprintingSpeed * Time.deltaTime);
}
}
void Jump(){
bool isGrounded = Physics.CheckSphere(groundCheck.position, 0.1f, groundMask);
}
void Crouching(){
}
void Sliding(){
}
void Climbing(){
}
void WallRunning(){
}
}```
Answer:
You are declaring your variable move
multiple times.
float move = ...
should be move = ...
If you have better answer, please add a comment about this, thank you!
сохранение
Re: сохранение
вы можете помочь исправить ошибку??
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Re: сохранение
2rusbekov 10 фев 2014, 12:21
зачем использовать object[] если можно string[] и коверт во флоат float.Parse(string) и pos должен быть Vector3. в Instantiate.
object name = wordss[ii]; он что должен строку инстанциировать? Скорее надо загрузку префаба с таким именем грузить из Resources
GameObject.FindGameObjectWithTag(«Circle»).transform.position в строке выглядит так «Vector3(1, 1, 1)». и если его присвоить переменной она не станет снова Vector3
Still alive…
-
2rusbekov - Адепт
- Сообщения: 1409
- Зарегистрирован: 06 апр 2012, 12:57
- Откуда: Бишкек
Re: сохранение
kolya9898 10 фев 2014, 15:05
2rusbekov писал(а):зачем использовать object[] если можно string[] и коверт во флоат float.Parse(string) и pos должен быть Vector3. в Instantiate.
object name = wordss[ii]; он что должен строку инстанциировать? Скорее надо загрузку префаба с таким именем грузить из Resources
GameObject.FindGameObjectWithTag(«Circle»).transform.position в строке выглядит так «Vector3(1, 1, 1)». и если его присвоить переменной она не станет снова Vector3
Смысле? название префаба Circle(1-2-3-4-5-6-7-8-9-10) -забыл написать Photon.
Дак, а как в юньке сделать чтобы через обычный Instantiate по названию блок респавнить в [RPC]
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Re: сохранение
kolya9898 10 фев 2014, 20:44
string[] wordss = wordsl.Split(new string[] { «|» }, StringSplitOptions.RemoveEmptyEntries);
string name = wordss[1/wordss.Length];
string poss = wordss[2/wordss.Length];
Debug.Log (name+»:»+poss);
помогите преобразовать string poss в vector3
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Re: сохранение
kolya9898 10 фев 2014, 21:23
help me
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Re: сохранение
2rusbekov 11 фев 2014, 07:48
Всем лень писать такое. Хочешь чтобы написали, плати, за 500 золотых допишу твой код)))
Still alive…
-
2rusbekov - Адепт
- Сообщения: 1409
- Зарегистрирован: 06 апр 2012, 12:57
- Откуда: Бишкек
Re: сохранение
kolya9898 11 фев 2014, 11:30
помогите преобразовать string poss в vector3
Используется csharp
Vector3 poss = Convert.ToSingle(wordss[2/wordss.Length]);
error CS0029: Cannot implicitly convert type `float’ to `UnityEngine.Vector3′
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Re: сохранение
2rusbekov 11 фев 2014, 11:42
Сохраняй так что ли pos.x + «/» + pos.y + «/» + pos.z
а потом сплит по слешу и new Vectro3(poss[0], poss[1], poss[2]) с преобразованием во флоат
Или подключи жсон библу какую нибудь и не парься.
Still alive…
-
2rusbekov - Адепт
- Сообщения: 1409
- Зарегистрирован: 06 апр 2012, 12:57
- Откуда: Бишкек
Re: сохранение
beatlecore 11 фев 2014, 11:45
Вот нашел вам материал для изучения по сериализации, десериализации классов в юнити, соответственно решение вашей проблемы, пишите сразу в бинарник ваши сохранения.
-
beatlecore - Старожил
- Сообщения: 964
- Зарегистрирован: 05 фев 2013, 21:26
- Откуда: Sun Crimea
- Skype: beatlecore
загрузка
kolya9898 11 фев 2014, 18:35
спасибо большое!
-
kolya9898 - UNITрон
- Сообщения: 333
- Зарегистрирован: 15 июл 2013, 19:28
- Откуда: Челябинск
- Skype: kolyan9898
Вернуться в Почемучка
Кто сейчас на конференции
Сейчас этот форум просматривают: Yandex [Bot] и гости: 22
Shinyo 0 / 0 / 0 Регистрация: 02.06.2020 Сообщений: 6 |
||||
1 |
||||
02.06.2020, 18:59. Показов 2107. Ответов 3 Метки rotation, unity2d (Все метки)
Подскажите, как избавиться от ошибки error CS0029: Cannot implicitly convert type ‘UnityEngine.Quaternion’ to ‘UnityEngine.Vector3’ в этом коде
Добавлено через 30 минут
__________________
0 |
11075 / 7639 / 1179 Регистрация: 21.01.2016 Сообщений: 28,684 |
|
03.06.2020, 06:49 |
2 |
Shinyo, должно быть очевидно (из сообщения компилятора), что вы пытаетесь выполнить некорреткное присвоение.
1 |
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
03.06.2020, 08:46 |
3 |
Решение p = transform.eulerAngles; наверное.
1 |
vk.com/pppoe252110 62 / 43 / 21 Регистрация: 31.05.2019 Сообщений: 251 |
|
03.06.2020, 09:42 |
4 |
Используйте кватернионы
1 |
please help, i’m currently working on a brick breaker game and working on paddle script
but it shows error on line 17, i don’t know how to change float to vector3
using UnityEngine;
using System.Collections;
public class Paddle : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);
float mousePosInBlocks = Input.mousePosition / Screen.width * 16;
paddlePos.x = Mathf.Clamp(mousePosInBlocks, 0.5f, 15.5f);
this.transform.position = paddlePos;
}
}
here is the script combined both answers
public class Paddle : MonoBehaviour {
Vector3 mousePosInBlocks;
Vector3 paddlePos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);
mousePosInBlocks = Input.mousePosition / Screen.width * 16;
paddlePos.x = Mathf.Clamp(mousePosInBlocks.x, 0.5f, 15.5f);
this.transform.position = paddlePos;
}
}
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0029 |
Compiler Error CS0029 |
07/20/2015 |
CS0029 |
CS0029 |
63c3e574-1868-4a9e-923e-dcd9f38bce88 |
Compiler Error CS0029
Cannot implicitly convert type ‘type’ to ‘type’
The compiler requires an explicit conversion. For example, you may need to cast an r-value to be the same type as an l-value. Or, you must provide conversion routines to support certain operator overloads.
Conversions must occur when assigning a variable of one type to a variable of a different type. When making an assignment between variables of different types, the compiler must convert the type on the right-hand side of the assignment operator to the type on the left-hand side of the assignment operator. Take the following the code:
int i = 50; long lng = 100; i = lng;
i = lng;
makes an assignment, but the data types of the variables on the left and right-hand side of the assignment operator don’t match. Before making the assignment the compiler is implicitly converting the variable lng
, which is of type long, to an int. This is implicit because no code explicitly instructed the compiler to perform this conversion. The problem with this code is that this is considered a narrowing conversion, and the compiler does not allow implicit narrowing conversions because there could be a potential loss of data.
A narrowing conversion exists when converting to a data type that occupies less storage space in memory than the data type we are converting from. For example, converting a long to an int would be considered a narrowing conversion. A long occupies 8 bytes of memory while an int occupies 4 bytes. To see how data loss can occur, consider the following sample:
int i = 50; long lng = 3147483647; i = lng;
The variable lng
now contains a value that cannot be stored in the variable i
because it is too large. If we were to convert this value to an int type we would be losing some of our data and the converted value would not be the same as the value before the conversion.
A widening conversion would be the opposite of a narrowing conversion. With widening conversions, we are converting to a data type that occupies more storage space in memory than the data type we are converting from. Here is an example of a widening conversion:
int i = 50; long lng = 100; lng = i;
Notice the difference between this code sample and the first. This time the variable lng
is on the left-hand side of the assignment operator, so it is the target of our assignment. Before the assignment can be made, the compiler must implicitly convert the variable i
, which is of type int, to type long. This is a widening conversion since we are converting from a type that occupies 4 bytes of memory (an int) to a type that occupies 8 bytes of memory (a long). Implicit widening conversions are allowed because there is no potential loss of data. Any value that can be stored in an int can also be stored in a long.
We know that implicit narrowing conversions are not allowed, so to be able to compile this code we need to explicitly convert the data type. Explicit conversions are done using casting. Casting is the term used in C# to describe converting one data type to another. To get the code to compile we would need to use the following syntax:
int i = 50; long lng = 100; i = (int) lng; // Cast to int.
The third line of code tells the compiler to explicitly convert the variable lng
, which is of type long, to an int before making the assignment. Remember that with a narrowing conversion, there is a potential loss of data. Narrowing conversions should be used with caution and even though the code will compile you may get unexpected results at run-time.
This discussion has only been for value types. When working with value types you work directly with the data stored in the variable. However, .NET also has reference types. When working with reference types you are working with a reference to a variable, not the actual data. Examples of reference types would be classes, interfaces and arrays. You cannot implicitly or explicitly convert one reference type to another unless the compiler allows the specific conversion or the appropriate conversion operators are implemented.
The following sample generates CS0029:
// CS0029.cs public class MyInt { private int x = 0; // Uncomment this conversion routine to resolve CS0029. /* public static implicit operator int(MyInt i) { return i.x; } */ public static void Main() { var myInt = new MyInt(); int i = myInt; // CS0029 } }
See also
- User-defined conversion operators