How can I change/set the 3d cube clicking area? - c#

Since the keypad don't have buttons I added cubes to each number and attached a script to each cube so when clicking on a cube it will show it's number in the top area.
For example Key 1 (Cube) when I click on it when the game is running it's not firing the click on all the cube area same for all the other cubes :
When I click on the cube of key 1 it's working only on the left bottom area mostly on that sides. Even if the cube is covering the whole key area.
This is how it looks like when I uncheck the cubes mesh renderer :
Then when running the game and clicking on a cube : it's showing the number in the Security Keypad Text(Text Mesh)
This is the script attached to each cube :
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
public class SecurityKeypadKeys : MonoBehaviour
{
public TextMesh text;
private void Start()
{
text = GameObject.Find("Security Keypad Text").GetComponent<TextMesh>();
}
private void OnMouseDown()
{
string[] digits = Regex.Split(transform.name, #"\D+");
foreach (string value in digits)
{
int number;
if (int.TryParse(value, out number))
{
text.text = value;
}
}
}
}
The main problem is that on most of the cubes you need to click on specific point/small area to make it work and I want it to be working trigger when you click on each cube at any place on the cube.

Try the RaycastExample by robertbu code here and put it on a script. OnMouseDown() requires nothing else be in the way. That code will tell you if something is in the way. Also, try moving everything closer as OnMouseDown() has a depth limit to its raycast.
I recreated your above example, and it works perfectly, so something else must be wrong.

Related

show text when clicking on a 3D object

I am fairly new to Unity and am currently working on a small project.
My problem is this.
I want to display text when I click on the cube.
I have a total of four different cubes, all of which should display different text when clicked.
The solution I have so far works, but of course now when I click on the cubes the same text comes up and if I assign each cube its own text they all appear at once.
The cubes should also rotate and when clicked on just stop and display the text.
I tried it with the Event Trigger System and assign different texts, but without success.
Any suggestion for a solution?
I tried it with the Event Trigger System and assign different texts, but without success.
Any suggestion for a solution?
enter image description here
You are using input.GetMouseButtonDown, when you click anywhere all
the boxes run the same code, you don't specify which box is clicked
you only looking for a click, I suggest you use raycast to send a
ray to detect which box you are clicking and run ,
Add this script to the camera or player and give all the boxes gameobject a "Box" Tag :
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Transform objectHit = hit.transform;
if (objectHit.CompareTag("Box"))
{
objectHit.GetComponent<Rotator>().RotateObject();
}
}
}
}
add this function to the Rotator Script and remove the code from update :
public void RotateObject()
{
if (rotateObject)
{
rotateObject = false;
Text.SetActive(true);
}
else
{
rotateObject = true;
Text.SetActive(false);
}
}
}

UI text Movement

How to move a UI text relative to Camera movement in Unity?
Want to move a UItext relative to camera movement in unity.Tried code exanples such as
using UnityEngine;
using System.Collections;
public class SortingLayerExposer : MonoBehaviour
{
public string SortingLayerName = "Default";
public int SortingOrder = 0;
void Awake ()
{
gameObject.GetComponent<MeshRenderer> ().sortingLayerName = SortingLayerName;
gameObject.GetComponent<MeshRenderer> ().sortingOrder = SortingOrder;
}
}
But not able to move my text realtive to camera.
Easiest would be to add the texts to the camera-gameobject as children. They will automatically follow the camera. If you need to adjust the position further by script, you can modify the texts localpositions - as this will keep it relative.
Using the canvas builtin gameobject type, everything attatched under the canvas will follow the camera and stay in position relative to screensize. you can also lock ui elements in specific locations on the screen using anchor points

How to Change Color of Game Object When Clicked in Unity?

I'm trying to create the board game Hex. Player One at the bottom being yellow and Player Two at the top being blue. When Player One clicks a hex it should become yellow and when Player two clicks a hex it should become blue.
I've created this Hex Map using a prefab and now I want to be able to change the color of each tile when I click on it (The yellow hexes you see will be transparent but the sprite I imported is yellow which is why the color on the Sprite Renderer is white even though the hexes look yellow).
Btw, as of right now changing the color in the Sprite Renderer changes the color of all the hexes.
I followed quill18creates's tutorial to make the Hex Map except I did it in 2D instead of 3D.
https://www.youtube.com/watch?v=j-rCuN7uMR8
As of write now my Color Change script isn't working at all. I was trying to have it so when it receives one click it changes to yellow. Then the next click to blue, the next to yellow, and so on. Since each player only get's one click.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorChange : MonoBehaviour {
public Color[]colors; // allows input of material colors in a set sized array
public SpriteRenderer rend; // what are we rendering? the hex
private int index = 1; //initialize at 1, otherwise you have to press the ball twice to change color
// Use this for initialization
void Start () {
rend = GetComponent<SpriteRenderer> (); // gives functionality for the renderer
}
// Update is called once per frame
void onMouseDown () {
// if there are no colors present nothing happens
if (colors.Length == 0){
return;
}
if (Input.GetMouseButtonDown(0)){
index += 1; // when mouse is pressed down we increment up to the next index location
// when it reaches the end of the colors it stars over
if (index == colors.Length +1){
index = 1;
}
print (index); // used for debugging
rend.color = colors [index - 1]; // this sets the material color values inside the index
}
} //onMouseDown
}
How should I go about implementing this? Any help would be much appreciated!
First things first, you need to properly capitalize OnMouseDown() for it to get called.
After that, since you're using a SpriteRenderer, you'll need to add a collider to detect mouse click events. As mentioned in the OnMouseDown() documentation:
This event is sent to all scripts of the Collider or GUIElement.
Since you have neither, on your prefab, click Add Component > Polygon Collider 2D and it'll automatically create the proper geometry for your sprite (assuming that everything outside the hex is transparent).
Finally, remove your check against Input.GetMouseButtonDown(0). OnMouseDown is already capturing the fact that the mouse was clicked and the specific instance running OnMouseDown() was the instance that was clicked.
add collider and rigid body to your prefab
then capital O in OnMouseDown and delete "if (Input.GetMouseButtonDown(0)){"
Input.GetMouseButtonDown(0) return true when player click anywhere which is not what you want
public Color[] colors; // allows input of material colors in a set sized array
public SpriteRenderer rend; // what are we rendering? the hex
private int index = 1; //initialize at 1, otherwise you have to press the ball twice to change color
// Use this for initialization
void Start()
{
rend = GetComponent<SpriteRenderer>(); // gives functionality for the renderer
}
// Update is called once per frame
void OnMouseDown()
{
// if there are no colors present nothing happens
if (colors.Length == 0)
{
return;
}
index += 1; // when mouse is pressed down we increment up to the next index location
// when it reaches the end of the colors it stars over
if (index == colors.Length + 1)
{
index = 1;
}
print(index); // used for debugging
rend.color = colors[index - 1]; // this sets the material color values inside the index
} //onMouseDown

Forcing Sprite Renderer to Render a Sprite

using UnityEngine;
public class PlayerLoad : MonoBehaviour
{
[SerializeField]
private Sprite pSprite;
private void Start()
{
LoadSprite(this.gameObject, pSprite);
}
void LoadSprite(GameObject p1, Sprite pSprite = null) // p1 = the player's gameobject
{
var sr = p1.GetComponent<SpriteRenderer>();
if (sr == null)// If no sprite renderer exist
{
sr = p1.AddComponent<SpriteRenderer>();
}
if (sr != null && !sr.enabled)// If sprite renderer exist but isn't active
{
sr.enabled = true;
}
if (sr.sprite == null)// If no sprite exist, adds one
{
p1.GetComponent<SpriteRenderer>().sprite = pSprite;
}
}
}
Ok, so I'm having an issue to where sometimes my player's sprite seems to be invisible. As of now, I can build the project onto my mobile device and everything works fine. However, when the second level is completed (Right now I only have two levels I'm using for testing) the game goes to the Death scene. Then it ask's the user to continue or quit. If continue, the player is taken to the last level reached. Code works, but the sprite is now invisible. Sometimes I can pause the game, quit and return to the main menu, click play again and start over and the player appears again. Other times it makes it worse because the bullets even fail to render. I have no clue as to what could cause such a thing. SO I have this code in hopes of forcing the sprite to render whether it wants to or not.
Here's a screenshot of the mobile screen:
To the right you can see the bullets firing but the player cannot be seen. You can tell the player is moving by the offset in the bullet trajectory. (If you look close)
I'm using Unity 2019.0.1a Beta

How do i use the animator avatar mask to combine two animations?

I want to combine weapon aiming idle with humanoidwalk.
So in the script when i click on the mouse right button it will aim and then when i press W it will start walking.
Now with the animator controller and script i have i can make right click on the mouse button and it will aiming but won't walk or i can just press W and it will walk with aiming. But i want to first right click and aiming and then press W and walk.
The screen shot is on my main layer the base layer:
The Aiming state is with weapon idle animation. And two transitions using parameter name Aiming type bool one transition set to true the other to false.
With this i can make right click button on mouse and aiming but not walking.
The second screenshot show the blend tree i did when making double click on Movement it's getting to the blend tree:
Using this blend tree with the script when i press on W it will walk and aiming the same time.
Now i tried to create a new layer with a avatar mask to make that when i click mouse right button it will first aim and then when pressing W it will walk. But it's not working.
In this layer i have only weapon aiming idle state with the weapon idle animation.
What should i do here else ? And what should i add/change in the script ?
The script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Soldier : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
var inputVelx = Input.GetAxis("Horizontal");
var inputVely = Input.GetAxis("Vertical");
transform.Rotate(0, inputVelx, 0);
anim.SetFloat("VelX", inputVelx);
anim.SetFloat("VelY", inputVely);
if (Input.GetMouseButtonDown(1))
{
anim.SetBool("Aiming", !anim.GetBool("Aiming"));
}
}
private void FootStep()
{
}
}
The main goal: To be able to click on mouse right button for aiming and then pressing W and walking.

Categories

Resources