I want create menu with buttons. Template button is cloned and placed in vertical layout. It worked but in the middle of work there is strange effect of rendering only text child od button, additionally gameobjects do not have width, are outside of canvas. On the screen , in the center is my template button, goal is to have two columns of buttons on left and right side.
using UnityEngine;
using UnityEngine.UI;
public class DivideDownUI : MonoBehaviour {
void Start () {
createBtnsRow(transform.Find("PanelLeft"));
createBtnsRow(transform.Find("PanelRight"));
}
void createBtnsRow(Transform panel)
{
for(int i = 1; i <= 10; i++)
{
GameObject btn = Instantiate(transform.Find("BtnTpl").gameObject);
btn.transform.parent = panel;
btn.SetActive(true);
btn.transform.Find("Text").gameObject.GetComponent<Text>().text = "" + i;
}
}
}
`
Resolved:
There was problem with positioning: After using rect transform instead of padding of layout group works as espected.
Related
How can i draw this line on my canvas and image, BUT under text?
so basically the render order should be this:
canvas
image
line
text
so text would be on top of every one of them.
right now i am almost there, but the line is over the text.
i am using world space on my canvas, and the event camera is set to Main Camera.
Picture
Add a "canvas" in the Hierarchy.
Add a "Image" under the "canvas" in the Hierarchy.
Add a "GameObject" under the "Image" in the Hierarchy.
Add a C# script in the Assets. The C# script named as "NewBehaviourScript".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class NewBehaviourScript : MaskableGraphic
{
Static NewBehaviourScript self;
NewBehaviourScript()
{
self = this;
}
// To redraw from outside this class, call NewBehaviourScript.redraw()
static public void redraw()
{
print("redraw");
self.SetAllDirty();
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
UIVertex vertex = UIVertex.simpleVert;
vertex.color = Color.red;
// draw a diagonal red line from bottom left to top right
// first triangle
vertex.position = new Vector2(0, 0); // lower left position
vh.AddVert(vertex);
vertex.position = new Vector2(canvas.pixelRect.width+2, canvas.pixelRect.height);
vh.AddVert(vertex);
vertex.position = new Vector2(canvas.pixelRect.width-2, canvas.pixelRect.height);
vh.AddVert(vertex);
// second triangle
vertex.position = new Vector2(2, 0);
vh.AddVert(vertex);
vertex.position = new Vector2(-2, 0);
vh.AddVert(vertex);
vertex.position = new Vector2(canvas.pixelRect.width, canvas.pixelRect.height);
// position it on the upper right.
vh.AddVert(vertex);
// draw two elongated triangles to form a straight line
vh.AddTriangle(0, 1, 2); // only triangles can be drawn
vh.AddTriangle(3, 4, 5); // only triangles can be drawn
}
}
Click the "GameObject" to show Inspector view, and click "Add component" button.
Add ""Canvas Renderer" into the "GameObject".
Drag "NewBehaviourScript" (in the assets) and drop it on the GameObject (in Hierarchy).
Add a "Text (Legacy)" under the "GameObject" in the hierarchy
With screen captured guide is here. This is an article I wrote.
https://kuukaix.hatenablog.com/entry/2022/10/02/181043
I'm trying to get all tiles around the player in unity 2d tileset.
What I would like to happen when player presses U I Would like to get all tiles surrounding the player including the one underneath the player or simply the one 1 tile in front of them.
I'm trying to make a farming Game where when the player pulls out an item it will highlight on the tilemap where they are about to place it.
Please note I'm not asking for full code, I just want what ever solution allows me to get tiles near the players position
Edit, found a solution by editing someone elses code but im not sure if there's a better way, if not I would also like this to work based on player rotation currently it places a tile above the player. Code Source https://lukashermann.dev/writing/unity-highlight-tile-in-tilemap-on-mousever/
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Tilemaps;
public class PlayerGrid : MonoBehaviour
{
private Grid grid;
[SerializeField] private Tilemap interactiveMap = null;
[SerializeField] private Tilemap pathMap = null;
[SerializeField] private Tile hoverTile = null;
[SerializeField] private Tile pathTile = null;
public GameObject player;
private Vector3Int previousMousePos = new Vector3Int();
// Start is called before the first frame update
void Start()
{
grid = gameObject.GetComponent<Grid>();
}
// Update is called once per frame
void Update()
{
var px = Mathf.RoundToInt(player.transform.position.x);
var py = Mathf.RoundToInt(player.transform.position.y);
var tilePos = new Vector3Int(px, py, 0);
if (!tilePos.Equals(previousMousePos))
{
interactiveMap.SetTile(previousMousePos, null); // Remove old hoverTile
interactiveMap.SetTile(tilePos, hoverTile);
previousMousePos = tilePos;
}
// Left mouse click -> add path tile
if (Input.GetMouseButton(0))
{
pathMap.SetTile(tilePos, pathTile);
}
// Right mouse click -> remove path tile
if (Input.GetMouseButton(1))
{
pathMap.SetTile(tilePos, null);
}
}
}
try to use the layer field inside the inspector, you can create new Layers inside the Project Manager and there you can easily create Layers like "Background" "Scenery" "Player" "Foreground".. after this you can assign them individually to your Tiles also its important to have different grids otherwise you will not be able to assign different layers to it i hope it worked already
I am trying to add 100 dynamically created buttons to a scroll view in Unity, but I have a problem letting the scroll view automatically adjust the width of the buttons to match the width of my screen.
When I tried to add the buttons manually it worked fine , but when I do this by code I get another results.
The code I am using :
public GameObject button;
public GameObject scrollviewcontents;
void Start()
{
for (int i =0; i<=100;i++) {
GameObject dbutton = Instantiate(button);
dbutton.name = i.ToString();
dbutton.transform.parent = scrollviewcontents.transform;
}
}
and The results I get :
Results
Results with comments
I just want the buttons to look like as they are added manually, any help ???
By default when instantiating an object the object keeps the same world space position, rotation and scale as before. try this instead:
dbutton.transform.SetParent(scrollviewcontents.transform, false);
Game View- Camera Display
When I click the Space Bar for the player to jump, the Display drop down menu pops up and the player doesn't jump. However, the player can move upon all key presses.
Here's the information that I have:
1) Everything worked and functioned properly.
2) I added a health bar to my boss.
3) I created a second canvas (First canvas was for my Player's HP).
4) I made the Boss HP bar render mode: World Space.
5) I attached the canvas to the boss controller in the hierarchy as a child.
6) The code I use for Player Jump is Input.GetKeyDown(KeyCode.Space).
7) The mouse curser is inside the Game View whilst testing the SpaceBar Jump.
8) I'm developing in Unity 2018 5.3 2D mode.
Official Question('s):
1) Why does the Spacebar causing the camera display drop menu to appear?
2) How do I fix this?
Edit / Additional Content:
Here's my Jump script
public float jump1 = 5.0f;
private bool onGround;
//private bool dblJump; //Not implemented yet
public Rigidbody player;
void Start () {
player = GetComponent<Rigidbody>();
onGround = true;
}
// Update is called once per frame
void Update () {
if (onGround == true) {
if (Input.GetKeyDown(KeyCode.LeftShift))// KeyCode.Space
{
player.velocity = new Vector3(0, jump1, 0);
onGround = false;
// Debug.Log("The onGround is False");
}
}
}
Keep in mind that I have temporarily changed my jump to LeftShift. However, my problem persist with the space bar, even when I click it with left shift as my jump. SpaceBar seems to summon the drop down menu for the camera display. (I can't seem to catch the drop down menu with a screen shot because it goes away upon a click)
Also Note - I'm inside a class called PlayerJump : MonoBehavior.
It seems like it's a known issue with some versions of Unity 5.3, I have a few solutions you can try :
Drag you game window somewhere else in the editor
Enable the "Maximise on play" button
Attach this script to your drop-down element :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DropdownScript : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
void Start()
{
dropDown = GetComponent<Dropdown>();
dropDown.interactable = false;
}
public void OnPointerEnter(PointerEventData ped)
{
dropDown.interactable = true;
}
public void OnPointerExit(PointerEventData ped)
{
dropDown.interactable = false;
}
}
Otherwise update you Unity version if it's not the latest release? I am not experiencing this issue but many other users are apparently.
I am using UGUI to make a Novice guide to guide people to play my game.
And need the whole UI be mask, but some rectangular areas to be lighted.
How to do?
Create a new gameobject and add a image component to it. Create a image with transparent areas where you want your ui to be visible. Assign that image to the image component. Then add a mask component
Put your other gui elements inside this gameobject so that is could overlap and hide everything except transparent areas. Here is the picture of demo setup.
IMHO, what you want to achieve is not easy to be done perfectly in Unity. Here is my personal solution:
I put a black panel below every other GUI, so that it darkens my entire screen.
I put an empty game object called BrightRoot below the panel, so that everything under BrightRoot will float over and "brightened".
In my tutorial script, I add function to look for a UI game object by name and change its parent to the BrightRoot. In example:
// To brighten the object
GameObject button = GameObject.Find("PlayButton");
Tansform oldParent = button.transform.parent;
button.transform.SetParent(BrightRoot, true);
// To darken it again
button.transform.SetParent(oldParent, true);
The perfect solution would be to write a UI shader that darken any pixel outside some rectangles and brighten the inside. Then set that shader to all UI objects.
Editted:
This just another easy method, using UI Vertex effect. Just need to implement IsPointInsideClipRect, put this component to your UI objects, and set the rectangles list:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[AddComponentMenu("UI/Effects/Clip")]
public class Clip : BaseVertexEffect
{
// We need list of rectangles here - can be an array of RectTransform
public RectTransform[] ClipRects;
public override void ModifyVertices(List<UIVertex> vertexList)
{
if (!IsActive())
{
return;
}
bool isClipped = true;
for (int i = 0; i < count; i++)
{
UIVertex uiVertex = vertexList[i];
foreach (RectTransform rect in ClipRects)
{
if (IsPointInsideClipRect(rect, uiVertex.position))
{
isClipped = false;
break;
}
}
}
Color32 color = isClipped ? new Color32(0.5f, 0.5f, 0.5f, 0.5f) : new Color(1.0f, 1.0f, 1.0f, 1.0f);
for (int i = 0; i < count; i++)
{
UIVertex uiVertex = vertexList[i];
uiVertex.color = color;
}
}
private static bool IsPointInsideClipRect(RectTransform rect, Vector3 position)
{
// ...
}
}