So I'm new to unity and trying to create a cube programmatically at the start, and when you press the down arrow key it decrements gradually.
using System.Collections.Generic;
using UnityEngine;
public class LetThereBeLight : MonoBehaviour
{
public GameObject rubixCube;
public Vector3 newScale;
public Vector3 currentScale;`
void Start()
{
GameObject rubixCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
rubixCube.transform.localScale = new Vector3(10f, 10f, 10f);
rubixCube.transform.position = new Vector3(0, 0, 0);
currentScale = rubixCube.transform.localScale;
newScale = new Vector3(-1f, -1f, -1f);
}
void Update()
{
if (Input.GetKey(KeyCode.DownArrow)){
currentScale = newScale;
if(currentScale.x < 10){
print("Well at least this worked");
}
}
}
}
When I run the play button in unity, the cube is created and I receive no errors but the cube does not shrink when I press the down arrow key. However, I know that the size of the vector is decrementing because I tell it to print a message as a test and it does so. But there are no visible changes to the size of the cube in the viewer.
Also, I originally put
currentScale = rubixCube.transform.localScale;
in the void Update()
function rather than the void Start()
and it gave me an error Unassigned reference exception: The variable rubixCube of LetThereBeLight has not been assigned
but shouldn't it not matter what function it is in whether it is called upon start or looped over because I already made rubixCube
a public GameObject outside of both functions?
Does anyone know how to solve this? Why doesn't this script work?
CodePudding user response:
Two issues:
In the
Start
you doGameObject rubixCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
which creates a local variable and hides the class field with equal name
rubixCube
!=> The class field
rubixCube
you later try to use inUpdate
is never assigned!In
Start
it should rather simply berubixCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Then in
Update
you docurrentScale = newScale;
You are changing the field
currentScale
, which is aVector3
value ... but that is all.You are not actually changing the
Transform
component on theGameObject
itself at all, so the cube in your game is not actually being affected at all by this code.You rather have to actually assign something back to the property
currentScale = newScale; rubixCube.transform.localScale = currentScale;
CodePudding user response:
I tried to modify your code, I searched for information, and clicked the "CreaterubixCube" button in the OnGUI() function to call the "CreatePrimitive" method, thereby creating a rubixCub object and adding its position attribute. I also just learned unity3d.