#archived-code-general

1 messages · Page 322 of 1

hoary sparrow
#

What's the best way to check if a UI element overlaps any other UI element?

jaunty light
#

In the following code I am trying to flip a sprite based on an enumerator. However the flips don't get applied to the sprite.
Does anyone know what I am doing wrong here?

private void ShowSprites()
{
    List<SpriteRenderer> finalSprites = new List<SpriteRenderer>();
    foreach (var tuple in gameLogic.chosenBlocks.Values)
    {
        finalSprites.Add(AlterSprite(tuple.Item1, tuple.Item2, tuple.Item3));
        slots[finalSprites.Count-1].style.backgroundImage = new StyleBackground(finalSprites[finalSprites.Count - 1].sprite);
    }
}

private SpriteRenderer AlterSprite(SpriteRenderer texture, Flip flipOption, Rotation rotateOption)
{
    switch (flipOption)
    {
        case Flip.none: texture.flipX = false; texture.flipY = false; break;
        case Flip.flipX:  texture.flipX = true; texture.flipY = false; break;
        case Flip.flipY: texture.flipY = true; texture.flipX = false; break;
        case Flip.flipXY: texture.flipX = true; texture.flipY = true;  break;
        default: break;
    }
    return texture;
}
knotty sun
jaunty light
#

Valid but that's because I updated the code. Just trying to have it functional

knotty sun
#

the obvious thing to do is add some debugs to AlterSprite as you cannot see from that code what exactly is being passed in

jaunty light
#

the returned texture is correct

#

let me send another screenshot

#

Updated the code slightly. Not the most elegant solution either, but got rid of the list.

  int i = 0;
  foreach (var tuple in gameLogic.chosenBlocks.Values)
  {
      slots[i].style.backgroundImage = new StyleBackground(AlterSprite(tuple.Item1, tuple.Item2, tuple.Item3).sprite);
      i++;
  }
#

I supposed it I call .sprite it accesses the source sprite and not the updated one

somber nacelle
#

you do know that the flip variables only affect the sprite renderer and how it displays whatever sprite is assigned to it, not the actual sprite texture, right?

knotty sun
#

beat me to it

jaunty light
#

How do you suggest to go about it?

#

What I wanna do is show 3 sprites in my UI. Each of them altered individually by flipping or rotating

#

but with the same original sprite

swift falcon
#

Hello, I am trying to spawn multiple rooms randomly and use this code to check and make sure they do not overlap, but it work very inconsistently. Is there something wrong with my logic or should you not try to spawn mutiple rooms and check for overlaps on the same frame?

plucky inlet
#

Hey everyone, I am wondering, if its possible to extent the gameobject class, so I can use a simple toggle method in the UI buttons? I kniow its working codewise, but it is not showing up in the dropdown, which I guess is the issue of it being a sealed class probably?

#

To clarify, I am using this in my extensions class, which is working in other classes of course. Any idea how to get it into the reflection of the UIbutton OnClick events?

public static void Toggle(this GameObject go)
        {
            go.SetActive(!go.activeInHierarchy);
        }
knotty sun
somber nacelle
# swift falcon Hello, I am trying to spawn multiple rooms randomly and use this code to check a...

since you aren't syncing the physics transforms and aren't waiting for physics to update then your physics queries won't have the most up to date information once you move those objects.
however it is generally better to generate the layout before spawning the rooms. then once the layout has been decided you just spawn rooms in the correct places based on the generated layout so you wouldn't even need these physics queries.

jaunty light
knotty sun
swift falcon
hoary sparrow
#

Currently I'm trying to make a UI object use "OnMouseEnter" and "OnMouseExit" events for objects in world space.

It works fine unless my actual mouse cursor is left over any UI.

What could I change with it to make it detect those regardless of what the actual mouse is hovering over?

private void Update()
{
    Position = new Vector3(_rectTransform.anchoredPosition.x + (Screen.width / 2), _rectTransform.anchoredPosition.y + (Screen.height / 2));

    _colliderHit = GetCollider2DFromScreenPosition(Position);

    if(_colliderHit != null && _colliderHit != _previousColliderHit) 
    {
        _colliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseEnter");

        if(_previousColliderHit != null) 
        { 
            _previousColliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseExit");
        }

        _previousColliderHit = _colliderHit;
        return;
    }

    if(_colliderHit == null)
    {
        if (_previousColliderHit != null)
        {
            _previousColliderHit.GetComponent<MonoBehaviour>().BroadcastMessage("OnMouseExit");
        }

        _previousColliderHit = _colliderHit;
        return;
    }
}

private Collider2D GetCollider2DFromScreenPosition(Vector2 screenPosition)
{
    Ray ray = Camera.main.ScreenPointToRay(screenPosition);

    RaycastHit2D hit2D = Physics2D.GetRayIntersection(ray);

    if (hit2D.collider != null)
        return hit2D.collider;
    else
        return null;
}
#

here is a gif of what I meant

#

Nvm, it was an error with a conditional I made earlier

mortal dagger
#

Has anyone ever gotten this error before, or knows how to fix it?

knotty sun
mortal dagger
#

Yes, i somehow cant accass an file stored in the unity cloud, but the strange thuing is, that the compiled / published programm ran just fine for 3 weeks and today it soemhow startet to not work

spark flower
#

hey guys, when i run code to move transform.position, it doesnt move the instance. but if i disable the animator attached to the character, then it moves the instance

#

when i turn on apply root motion in the animator then it works fine

deft timber
#

probably your animator overrides the transform.position

#

you set in code

fleet gorge
thin aurora
edgy stump
thin aurora
edgy stump
buoyant vault
#

Anyone know anything about asset bundling and storing assets in cloud to retrieve it on runtime using UnityWebRequestAssetBundle?

gray mural
#

Should I use #if UNITY_EDITOR with Application.isPlaying to increase the performance when the game is played outside of the editor?

tame nova
#

if you have stuff you only want running in editor then that could be useful yeah

#

you can also use the [Conditional("UNITY_EDITOR")] tag on methods

gray mural
#

Is there any way to make #if be shifted to the right as the other lines? It's fixed on the left.

gusty aurora
gray mural
gusty aurora
#

Anyone knows what if attributes created with CreateVFXEventAttribute are worth caching ?

gusty aurora
#

Similar question, is it worth caching the System.Actions ?

#

things like System.Action setCoroutineToNull = () => _coroutine = null;

leaden ice
#

Depends on the context

heady iris
#

You'll get less garbage allocated if you avoid creating a new anonymous function every frame

#

Storing it also means that you can subscribe to and unsubscribe from events with it

heady iris
#

(i don't remember if it also happens for event subscriptions, but i'd expect that to be the case)

#
foo.Bar(MyMethod);

resolving the MyMethod method group produces garbage

heady iris
#

subscribing to an event also generates garbage, but you get even more if you pass a method group

heady iris
latent latch
#

With a little more work you can skip out on EvenAttributes and just do graphic buffers with unmanaged data types reuse the buffers directly

heady iris
#

I stick the callback method into a System.Action<TheResult> field in Awake

#

it winds up producing zero allocations!

heady iris
#

an event has to be a lot more cautious; you can un-subscribe from an event while it's being invoked

knotty sun
#

yes, ColorType is not string

#

yes, that is the method signature required

#

yeah, on value changed take the value type of the element so Toggle takes a bool and Slider takes a float

wild sail
#

Hey guys I have a questions regarding code structure.
So I have coroutines, some are called only once, some can be called from update.
I have added a bool to each coroutine which represents if a coroutine is active or not.
The problem is, once you have a number of coroutines, it's hard to keep track of each bool and routine.

Is there a better way to do it?

knotty sun
#

A Flags enum could be a better option

rigid island
#

why not store the coroutines inside array of Coroutine[]

#

or list

#

bools seem wild use if you have many

naive swallow
dark tide
#

Hey guys, I'm having a lil bit of trouble implementing the rules for the day/night cellular automaton. I have the GoL and Seeds rules working, but for some reason the day/night rules aren't working. instead of showing what it's supposed to be showing, it is a chaotic growth instead. I tried replacing the day/night rules with the rules for the maze automaton, and it did the maze automaton perfectly- so the problem is certainly in the day/night rules. here is a bit of the compute shader with the rules in it: ```cs
if (current.r == 1 && current.g == 1 && current.b == 1)// GoL rules
{
if (GoLcount < 2 || GoLcount > 3)
{
next = 0.0; // Loneliness or overcrowding
}
else
{
next = float4(1, 1, 1, 1); // Survival
}
}
else if (current.r == 1 && current.g == 1 && current.b == 0)// Seeds rules
{
next = 0.0;
}
else if (current.r == 0 && current.g == 1 && current.b == 1)// Day/Night rules
{
if (DayNightcount == 6 || DayNightcount < 3)
{
next = 0.0;
}
else
{
next = float4(0, 1, 1, 1);
}
}
else
{ // if cell is dead
if (GoLcount == 3)
{
next = float4(1, 1, 1, 1);
}
else if (Seedscount == 2)
{
next = float4(1, 1, 0, 1);
}
else if (DayNightcount == 3 || DayNightcount == 6 || DayNightcount == 7 || DayNightcount == 8)
{
next = float4(0, 1, 1, 1);
}
else
{
next = 0.0; // Stay dead
}
}

#

(I hope I didn't just disobey a rule by sharing that much code 😅 )

#

some more explanation is probably necessary isn't it

knotty sun
#

DayNightCount == 6 on both sides does not seem correct. Also !code

tawny elkBOT
wild sail
dark tide
#

(also thanks I didn't know you could put "cs" to format it correctly :D done it)

finite willow
#

We're setting the targetFrameRate to 60, but we notice on high refresh rate monitors it is not respected. 180Hz shows 180 fps. This is on windows standalone.

        {
            Application.targetFrameRate = 60;
        }```
rigid island
#

also how are you checking fps

finite willow
knotty sun
finite willow
leaden ice
#

So yes

finite willow
#

admittedly, I dont totally understand vsync

leaden ice
#

That will sync you to the monitor refresh rate

dark tide
leaden ice
#

Or try to

finite willow
dark tide
#

oh wait I think I have something

knotty sun
dark tide
#

yep

#

done

#

thanks!

dark tide
#

classic oversight

#

thank you very much for pointing that out!

knotty sun
#

hmm, I did say == 6 on both sides seems incorrect

knotty sun
#

and that was without knowing the rules

dark tide
#

yeppeye

#

I just needed to look closer

#

darn it

#

anyway, I'm sure I'll have more cases like these- I just need to look closer and analyse more :D

knotty sun
#

yep, plug in values and run the code in your head, simple errors like this soon become apparent

dark tide
#

yep! thanks again!

gleaming veldt
#

hi! i'm having some trouble learning about instantiation. i'm currently working on a flappy bird clone... i've got the pipes moving across the screen but i want to have them spawn at varying heights once they move off screen. my question is how can i have the game instantiate a new pipe at a random height once it moves off screen?

#

currently my game just has the pipes move back to the intial x position when it moves off screen in its movement script

#

but ideally i'd want it to destory and instantiate a new pipe when it moves off screen

knotty sun
#

Instantiate can take a position, I suggest you read the documentation

dawn pike
#

Hi! I have 3 smaller projects and i would like to combine them to be able to use features from each of them, is there any good way to just fuse all 3 projects so that I can access the stuff i need and then later delete the rest?

knotty sun
dawn pike
#

Export asset exports the whole project?

knotty sun
#

it exports what you tell it to

gleaming veldt
dawn pike
knotty sun
raven ledge
#

hello i have a question ,i am a begginer can you make a modifiable excel file for player in unity

knotty sun
raven ledge
#

hmm so an external excel file is kinda imposible

knotty sun
#

not impossible but not easy without sufficient knowledge

zealous jay
#

Anyone know what to do about this?
Nothing I find online works.
I'm already set to VS 2022, tried regenerating project files, deleting library, deleting .vs file, deleting all the project files from the project folder manually, updating VS and VSTU, it just refuses to acknowledge that it's installed.

The one thing I suspect might be it is that I don't have Visual Studio Editor in my package manager, it doesn't show up even when I select All Packages.
I don't know if it's because it's not actually used anymore and the docs are outdated, or if something broke so that it doesn't show up for me.
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows

Could anyone maybe check their Packages/manifest.json and tell me what the package id and version for Visual Studio Editor are in theirs so I could try a manual import?

Connect Unity and Visual Studio and use Visual Studio Tools for Unity to support writing and debugging for cross-platform development.

knotty sun
dull barn
#

Im trying to spawn enemies randomly on a 2d top down scene, but the enemies can spawn right next to the player and damage him right away, is there a way to check the disance between the spawnpoint and the player and spawn it further away if too close?

raven ledge
raven ledge
#

ok thx for helping

neon zinc
raven ledge
#

i see thx for all the help

knotty sun
neon zinc
knotty sun
indigo verge
#

I want to serialize a list of classes that derive from an abstract class to JSON, but it's throwing an error, saying that I can't instantiate the abstract class.

#

Can anyone help me figure this out? I've tried looking up stuff on it, but I don't understand it.

knotty sun
lean sail
indigo verge
#

Gotcha

#

In this case, I'll probably just save a list for each derived class, then recompile them.

knotty sun
gleaming veldt
#

Why is my game camera not showing up here? I'm trying to set the camera for the UI Canvas

simple egret
#

(also not a code question, if you still have issues move your question to #💻┃unity-talk)

#

Input fields have a regex validation option if I remember correctly

rigid island
#

you need regex expression

#

I think ^[0-9a-fA-F]+$

humble spoke
#

Hi guys, I want to make interaction system, but it making ray only on X axis, not on Y, so it's working not correct, how can I fix it? Ray ray = new Ray(transform.position, transform.forward);

#

I need to change forward, but I don't know on what.

rigid island
#

forward is Z

simple egret
#

If you need to change forward, rotate your object. Currently it takes the local Z axis (blue arrow when you have the object selected) of the object this script is attached to.

leaden ice
#

Depends which direction you want

#

Forward is the object's z axis

gray mural
#

I have an object, which has a BoxCollider2D with the size Vector2.one. OverlapBox detects the object when the point is shifted on 1 to any direction, when the size is larger than ~0.95.
Why such a huge offset? I expect it not to return any object when the size is Vector2.one.

Physics2D.OverlapBox(point, Vector2.one * size, 0f);
humble spoke
humble spoke
#

Y/X

#

or Y/Z

rigid island
#

also this is like 3D game right ?

#

transform.right gives you the X axis of the object

simple egret
#

It does not always "point to the right" of your screen, if the object is rotated for example

#

Don't mix up world coordinates eg. Vector3.right (which always points right) and object coordinates transform.right

humble spoke
#

it doesn't care about Y

#

i can look at the sky, but it will think that I'm watching pn item

#

in upper you see it

rigid island
#

first of all put your gizmos in Local mode

humble spoke
rigid island
#

you never want to configure this stuff with Global on

humble spoke
humble spoke
rigid island
humble spoke
#

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class Interactor : MonoBehaviour
{
private float radius = 0.2f;
public LayerMask mask;
public TextMeshProUGUI textE;

public void Update()
{
    Ray ray = new Ray(transform.position, transform.forward);
    Debug.DrawRay(ray.origin, ray.origin + ray.direction * 1000, Color.red); // Отрисовка луча в дебаге

    RaycastHit hit;

    if (Physics.SphereCast(ray, radius, out hit, Mathf.Infinity, mask))
    {
        textE.gameObject.SetActive(true);
        if (Input.GetKeyDown(KeyCode.E))
        {
            Debug.Log(1);
        }
    }
    else
    {
        Debug.Log(0);
        textE.gameObject.SetActive(false);
    }
}

}

rigid island
#

this should just be
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red); // Отрисовка луча в дебаге

humble spoke
#

it is red ray in debug

rigid island
#

i know what it is my guy

humble spoke
rigid island
# humble spoke okay

now that you put it in Local mode could you show the origin of the Interactor object

rigid island
#

I think thats what making your visual look strange when looking up

humble spoke
#

the problem is that because of transform.forward this ray works only on Z axis

rigid island
#

is the Origin that has that script child to camera ?

humble spoke
#

Yes, to player, it has camera

#

I used asset with movement

rigid island
#

with whole hierarchy visible ,

humble spoke
rigid island
#

which one has the script ?

#

FirstPersonPlayer?

#

if so its wrong

#

put it on the PlayerCamera

humble spoke
#

okay

rigid island
humble spoke
#

No way bro it worked!!!!

#

script is now on camera

#

Thank you a lot! Дзякуй!

#

Nah, my problem was too stupid and easy😅

unborn holly
#

Hi, does anyone know that I can implement IAP or other payment gateway sdk to my game but not related with google play store?

humble spoke
unborn holly
humble spoke
#

The problem is that I don't know how too add thing like that in game

unborn holly
#

I was searching through Google some payment gateway, but couldn't really find :/

sly siren
#

hello i want to create a limited ranged of an ability in my game but i don't have idea of how to do that

tawny elkBOT
sly siren
rigid island
rigid island
#

place = new Vector3(_Hit.point.x, _Hit.point.y, _Hit.point.z);
why this a new vector3 if it can just be place = _Hit.point

unborn holly
sly siren
#

my script teleport my player I want add a to limit range like a spell in lol

rigid island
#
float dist = Vector3.Distance(player.position, rayhit.point);
if(dist <= maxRangeTeleport)
{
//Teleport
}```
#

You could also limit how far your raycast can go

unborn holly
humble spoke
gray mural
leaden ice
gray mural
leaden ice
#

You'd have to show a picture of the scene and explain where the objects are etc

#

Gizmos.DrawWireCube may help you too

ripe wave
#

need help how to make when A game Over screen pops up and the player coudn't use controls walk when player IsDead = true; the screen works perfect and pops up but the player still can use the controls like walk

leaden ice
#

Many options

ripe wave
young tapir
#

Is there an easy way to connect two rigidbodies using a joint through code? I'd just do it inside the editor but I can't easily get at one of them

rigid island
leaden ice
#

AddComponent

young tapir
#

I should specify, I can add the component to what I need, i just can't connect it to what I'd want to and can't figure out exactly how

#

it might be a bit more complex than it should be, actually..

leaden ice
#

What's confusing you

#

Set the connectedBody etc

rigid island
upper pilot
#

OnEnable is called before Awake when an object is a child of another object?
Wasn't it supposed to happen in an order of Awake -> OnEnable?
https://docs.unity3d.com/Manual/ExecutionOrder.html
What is the solution other than placing all my objects in a root of my hierarchy?

#

Trying to run this code:

    private void OnEnable()
    {
        Game.Instance.onInitComplete.RemoveListener(Init);

        if (Game.Instance.IsInitialized) Init();
        else Game.Instance.onInitComplete.AddListener(Init);
    }
#

Game.Instance is null, even tho Instance is created in Awake

brave furnace
#

Does anyone know if there is a C# equivalent to python's "eval()" function?

brave furnace
#

yeah, I found those, and was hoping somebody here had some obscure knowledge of a unity function that does this

#

oh well

lean sail
lean sail
brave furnace
latent latch
#

I would just make a data c# script and hardcode your formulas

lean sail
# brave furnace I want to make a scriptable object for a skill, where I can write the damage for...

If you have all the numbers present in some sort of collection, then you probably could do this by parsing the string though itd really be a lot slower. You could even go as far as defining an operation which takes 2 numbers and does an operation on them, then have a list of these visible in inspector. The real tedious part is gonna be having a lookup from some index or ID to number.
Any option is really gonna be slow in comparison to just defining them all in code and using like an enum to choose which formula to use

latent latch
#

you can do like semi parse stuff like building it like scratch using enums

brave furnace
#

Thx 😄 I think I might just think of it differently

upper pilot
#
    public void AddItem(int scriptableObjectIndex)
    {
        ItemData itemOwned = GetItemData(scriptableObjectIndex);
        if (itemOwned != null)
        {
            itemOwned.ItemCount += 1;
        }
        else
        {
            CreateItemData(scriptableObjectIndex);
        }
    }

    public void AddItem(ItemBaseSO itemBaseSO)
    {
        ItemData itemOwned = GetItemData(itemBaseSO);
        if (itemOwned != null)
        {
            itemOwned.ItemCount += 1;
        }
        else
        {
            CreateItemData(itemBaseSO);
        }
    }

Can this be improved? It's repeated code, I am getting/creating data from either an index or a SO.

#

The order is basically:
Index -> SO

So if I have SO already, then I skip that part of getting SO by index, but everything else is the same.
The thing is that I want the ability to use both, so an item data can be added, removed, returned by either using Index or itemBaseSO.

#

I can probably just improve it by taking out if itemOwned != null into its own function, but thats about it.

#

Actually even that I cant do hmm, maybe a callback but that seems like an overkill 😛

brave furnace
#

but if you know the scriptable object index, why can't you give it the SO instance?

lean sail
mossy snow
upper pilot
#

Yeah but if I remove int overload, then every script in the game has to get SO from database

#

Which is why I added it

#
            ItemBaseSO itemBaseSO = GameDatabase.Instance.ItemList[itemData.ItemIndexSO];
brave furnace
#

well there ya go

upper pilot
#

!code

tawny elkBOT
brave furnace
#
    public void AddItem(int scriptableObjectIndex)
    {
        ItemBaseSO itemBaseSO = GameDatabase.Instance.ItemList[itemData.ItemIndexSO];
        AddItem(itemBaseSO);
    }

    public void AddItem(ItemBaseSO itemBaseSO)
    {
        ItemData itemOwned = GetItemData(itemBaseSO);
        if (itemOwned != null)
        {
            itemOwned.ItemCount += 1;
        }
        else
        {
            CreateItemData(itemBaseSO);
        }
    }
upper pilot
#

oh

#

lol

#

I knew there has to be a simple way lol, thanks I will try that 😄

brave furnace
#

but I agree, the index argument is flimsy

latent latch
#

I give index to my SO

brave furnace
#

I'd recommend rephrasing the AddItem to AddItemFromIndex

latent latch
#

guid rather

#

cause guid is cool

upper pilot
#

I havent gone into guid route yet, its planned, but idk if it will happen for this game.

#

I will replace index with guid eventually

lean sail
#

Some form of ID is fine if this is loaded from file for example. Otherwise I dont really see a case where you'd need to add an item from using a number

upper pilot
#

so the function will be AddItem(string itemGUID)

#

Since this way it prevents errors of using index and saving it as that can change.
But I need to make sure GUID stays unique forever, which is why I havent gone there yet as I have other things that needs to be done 😄

#

Its loaded with Resource.Load

#

I store it in a List and I access it directly from a list by index(not ideal I know, but at some point I hope to use GUID instead, we will see if time allows)

#

This is funny cuz I already did your solution for another script, tho in a different order:

    public ItemData CreateItemData(int scriptableObjectIndex)
    {
        ItemData itemData = new ItemData();
        itemData.ItemIndexSO = scriptableObjectIndex;
        itemData.ItemCount = 1;
        Items.Add(itemData);

        return itemData;
    }

    internal ItemData CreateItemData(ItemBaseSO resultItem)
    {
        int itemSOIndex = GameDatabase.Instance.GetItemIndex(resultItem);
        return CreateItemData(itemSOIndex);
    }
#

Guess I need a break

brave furnace
#

your code scares me

#

so if this is how you plan to instantiate the ItemData, maybe create a constructor that takes ItemIndexSO and ItemCount as arguments for it?

swift falcon
#

in the console it keeps telling me that i need to assign a variable that i already assigned how do i fix this issue

#

heres my code

brave furnace
#

main camera is assigned in the inspector?

swift falcon
#

yeah

upper pilot
brave furnace
rigid island
swift falcon
swift falcon
rigid island
swift falcon
#

found it

#

THAT FIXED MY ISSUE

#

THANK YOU

steady wyvern
#

I'm following this 2D water tutorial that is just instantiating a bunch of circles each with their own rigidbodies and colliders. I like working with this simple method but the performance cost is kinda bad. I've heard of using DOTS but I want to check in with Unity discord before jumping into that. Would DOTS be the right move for this case?

languid hound
#

That does seem a bit extreme yeah. I personally made a bunch of transform points along the surface with a small circle collider then did the physics myself mostly

#

If something overlapped the point, find the velocity of that something and then displace the point and any surrounding points but gradually make the displacement smaller

#

I did some hacky velocity stuff that was a semi verlet integration sort of thing it's weird to explain

cosmic rain
cosmic rain
dense rock
#

Hey there, in my top down game, I want a weapon pickup to show an info box besides it when the player walks over it/is in reach to pick it up, along with the keybind to pick it up (fortnite as reference). Now one of the problems comes when theres multiple pickups the player steps on. How could I handle that? I don't have any idea on how to approach this info box at all.

rigid island
#

you could make it a WorldCanvas which would take care of easy positioning not worry about scale

#

depends how many you need on screen / look you can yse either like also ScreenToWorld forr regular UI

dense rock
#

I only want one info box at a time

rigid island
#

imo then the same worldcanvas that follows your player just for showing infos

dense rock
#

I'm just wondering if I should make a singleton info box manager and OnTriggerEnter put the pickup on a queue or smth

#

and OnTriggerExit remove itself from the queue. Then the Manager could take only the first one in the queue to display, right?

rigid island
#

yeah you can check in trigger what it is

dense rock
#

wdym check in trigger?

rigid island
dense rock
#

exactly, thats what confuses me 😅

rigid island
#

its up to you , do you want it based on distance or your player's FOV / Dot

dense rock
#

probably just distance

rigid island
#

doesnt fortnite show only the info box when cursor is on the actual mesh of floor item

dense rock
#

just want when the player stands ontop of a weapon item, it shows the info to pick it up.
Don't know how to handle that

rigid island
dense rock
#

thats an interesting approach, I'll think about that :)

rigid island
#

You could also just use a Physics Overlap

#

which reiqures no rigidbody on trigger or item

dense rock
#

do you have an idea how to handle when he stands ontop of multiple?

rigid island
#

sort it by distance

dense rock
#

i mean the player will have a rb anyways

rigid island
#

store them in an array

rigid island
dense rock
#

uh okay, so add it to an array and sort it everytime one is added?

rigid island
dense rock
#

oh yeah i can see that

#

thanks man, that was very helpful

#

i think i can do the rest on my own ^^

rigid island
#

np goodluck there

dense rock
# rigid island np goodluck there

sorry to ping you again, got some issues :')
How do I convert them from Collider2D[] to IPickable[]?
Do I sort them with some sorting algorithm or should I use Linq?

[SerializeField] private float pickupRange;

    [SerializeField] private IPickable[] pickups;

    void Update()
    {
        Collider2D[] cols = Physics2D.OverlapCircleAll(transform.position, pickupRange);

        cols[1].TryGetComponent(IPickable, out IPickable pick);
    }
rigid island
#

IPickable was an example lol make your specific class, didn't mean you actually copy that exact class

#

also try get is a boolean it returns true if component is found and stores it in the variable pick for example

barren patio
#

so a got a issue that i need fixing

dense rock
barren patio
#

is there a way to rotate a transform to have the same up as a ray cast normal without needing to manipulate euler rotation y?

rigid island
#

Layermasks for the Overlap

dense rock
#

alright, but the converting with a for loop is fine? I feel like there is a better alternative method that i just dont know about, but am probably wrong

rigid island
#

they are not very expensive for a handful, unless you start doing crazy amounts of work with more than thousands of iterations

#

and even then.. checking for component is nothin

barren patio
#

🗣️

dense rock
#

Thanks ^^

rigid island
dense rock
#

out of my knowledge too

rigid island
# dense rock Thanks ^^

if you want to improve performance Iwould suggest learning the nonalloc version of Overlap

barren patio
#

when you ray cast you can get a normal right, i want a transform to match that normal but without it affecting the y axis of the euler rotation

rigid island
#

make a new euler and pass its own euler y as value ?

barren patio
#

i've tried that and for some reason it decides to get wonky like it you changed the w axis in a quaternion

rigid island
#

hmm can you show what you tried

#

ideally you dont want to mess with eulerAngles directly

#

you want eulerangles to quaternion

barren patio
#

i've deleted basically all the rotation code i'm left with just this

#

var qerot = Quaternion.FromToRotation(TMP.transform.up, info.normal).eulerAngles;
var rot = new Vector3(qerot.x,qerot.y,qerot.z);

#

i don't know how to use the discord code thing to format sorry

#

ideally i'd like to chang rot.y to whatever id like

rigid island
#

!code

tawny elkBOT
dense rock
#

Does this make any sense?

pickups.OrderBy(x => Vector2.SqrMagnitude(x.transform.position - transform.position));
rigid island
#

careful with LINQ methods and how often you use that

dense rock
#

okay

rigid island
#

I dont recall if Vector2.SqrMagnitude is better than v2.Distance or not

dense rock
#

yes I think so

#

thats why I used that

barren patio
#
var qerot = Quaternion.FromToRotation(TMP.transform.up, info.normal).eulerAngles;
                    var rot = new Vector3(qerot.x,qerot.y,qerot.z);
somber nacelle
#

sqrMagnitude doesn't square root the result like Distance does so it is a bit better

rigid island
#

ahh ok

dense rock
#

How should I order them in the update method?

#

should I run a sorting algorithm?

rigid island
#

You could try it maybe running it betwen specific seconds instead of every frame , might improve some bit

#

in terms of sorting yes you need some compare method

dense rock
#

how about I check how many are overlapping, and only if that changes I check/update the list?

somber nacelle
#

do you need to sort them, or do you only need access to whichever is closest?

dense rock
#

only the closest

barren patio
#
var qerot = (Quaternion.FromToRotation(TMP.transform.up, info.normal) * TMP.transform.rotation).eulerAngles;
                    var rot = new Vector3(qerot.x,qerot.y,qerot.z);```
somber nacelle
dense rock
#

ohhh right

barren patio
#

i just want rot y to be whatever i want like placing a fan and still being able to modify rot y without it doing its own weird thing

rigid island
#

i'd have to test it

#

my head implodes with rotations sometimes

barren patio
#

ill try it, i think ive done something very similar

barren patio
rigid island
barren patio
#

do you mind vc?

rigid island
#

can't

#

record vid

barren patio
#

with your solution (idk if i butchered the implementation) it does this

#

perfect

#

on walls perfect until

#

you rotate and it does it on the global y

rigid island
#

oh Vector3.up is global

#

transform.up for local

#

if thats what you mean. I can't tell that much wha is going on vs whats supposed to look like

barren patio
#

i cant screen record but it when its transform.up it spins around like crazy

rigid island
#

what are you trying to do with this script exactly

#

like what is the mechanic here

barren patio
#

rotate along the local y axis

barren patio
#

trying to have this part be placable anywhere and it faces up with the normal but i want to rotate along the local y axis aswell but it just doesnt want to

#

eh ill just preprocess every variable and with what i finish ill then apply that to the transform

rigid island
#

raycast?

barren patio
#

yes

rigid island
#

so the knob is supposed to always be at the top on each normal of the cube?

#

or world up

barren patio
#

like how in a camera controller you can face any direction without the z axis

#

i figured something out thanks for helping

rigid island
#

raycast hitting itself?

swift falcon
#

if i want to find target direction its current position - target position right?

swift falcon
#

aw thanks

barren patio
#

unity is doing a unity

#

i really dont know how to fix this

#

i rotate the y axis in inspector

#

cool it turns left and right

#

i turn the z axis in inspector

#

COOL IT TURNS LEFT AND RIGHT

#

i turn x axis it rolls forwards and back

#

lemme record this on my phone i cant make this up

#

why is this happening

tough lily
#

Can anyone be a dev for my game you have to: know how to make a map, know how to make a player model, and you also have to have experience

cosmic rain
barren patio
cosmic rain
cosmic rain
tawny elkBOT
barren patio
cosmic rain
#

Wait, no. It is gimbal lock

tough lily
cosmic rain
# barren patio yep

But it's probably related to your code.
Does the issue happen outside of play mode?

barren patio
#

i disabled the script that cause that in that video

cosmic rain
#

So can we consider the issue fixed?

barren patio
#

i dont know

cosmic rain
#

Well, it sounded like the issue is was with the script and after you disabled it, it was gone..?

#

I'm not sure how else to interpret your previous message

barren patio
#

im just trying to find a way to align to a surface normal while still being able to rotate the along the up vector

cosmic rain
#

Around world up

barren patio
#

i mean the transform up

#

not world

cosmic rain
#

Which is the transforms up? I don't see the transform gizmo in the video

barren patio
#

the little knob is a indicator sorry for not showing

cosmic rain
#

So when you disable the script, it works?

barren patio
#

is there a way to vc?

lean sail
# barren patio is there a way to vc?

not in this server. though really, if you have a script which is affecting the rotation then maybe you should point that out instead of just saying the z axis isnt working.
If you need help with specific code then you should just ask about that, and look at the #854851968446365696 on how to ask

barren patio
#

i have asked and showed the code

#
cs
                    Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);
     
                    Vector3 rot = normRot.eulerAngles;
                    rot.y = rotation;
                    //
                    TMP.transform.eulerAngles = rot;
daring orchid
#

Anyone here has experience with ML Agents? Doing an enviroment where an agent needs to click a button, after the press of the button a platform with food on top will spawn. Agent needs to jump to the platform and collect the food. He learns quite quickly how to press the button but can't for anything I tried to jump to the platform. Can anyone help me? Tried multiple types of observations, using ray sensors, mixing both, nothing works. He spams jump on the edge of the innitial platform and doesn't jump to the desired platfom.

leaden ice
lean sail
# barren patio ``` cs Quaternion normRot = Quaternion.FromToRotation(Vector...

ah i scrolled up further, it seemed like the question started from the video. Though what do you mean you want to align to a surface normal and rotate around transform.up? Like which part of the object should align with the normal?
rotating it from inspector definitely will not follow this rule, and your code will constantly be fighting to set it based on this code.

barren patio
#

me head am hurt

barren patio
#

the funny remote is rotated to face the up of the surface (left of it), i want to rotate the romote around while keeping it attached to the surface

#

the surface can be facing any way so i want to rotate it regardless if the up vectors direction but follow along it

#

this is it with this code to direction it

#

Quaternion normRot = Quaternion.FromToRotation(TMP.transform.up, info.normal);

#

this is it with the same thing but using world uo vector

#

Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);

#

been trying to find a fix for the last 3 hours

#
if (Input.GetKeyDown(KeyCode.R))
                    {
                        rotation += 45;
                    }
                    //
                    
                    TMP.transform.position = info.point;
                    TMP.transform.Translate(-PlacingPart.PivotPoint.localPosition);
                                    //
                    Quaternion normRot = Quaternion.FromToRotation(Vector3.up, info.normal);
     
                    Vector3 rot = normRot.eulerAngles;
                    rot.y = rotation;
                    //
                    TMP.transform.eulerAngles = rot;
#

this is the code

#

the position part works perfectly fine, its the rotation that doesnt want to behave

#

info being a raycast variable

cosmic rain
barren patio
#

i dont want the world up to rotate i want the transform up to

cosmic rain
#

Yes, but that's exactly what you're not doing.

#

Can you answer my previous question?

barren patio
cosmic rain
#

You're not listening

barren patio
cosmic rain
#

Not that

barren patio
#

i want it to rotate on the transform up without it glitching around

cosmic rain
#

Can't you just do transform.up = hit.normal?

barren patio
#

uh. i never thought of that

#

Same result

#

maybe i should give up

latent latch
#

ew eulers

#

stick to Quaternion.AngleAxis

barren patio
#

what does that do exactly

latent latch
#

allows you to specify up and prevents gimbal

barren patio
#

really?? :0 thank youu

cosmic rain
# barren patio

It would also help if you don't record your screen from your phone but use a dedicated software for screen recording. It's really hard to look at...

cosmic rain
#

Obs studio for example

#

This part of the server(and dev communities in general) etiquette. It's not very nice to share photos/videos of your screen from your phone.

#

Make it easier for people to help you and you'll get better/more help

barren patio
#

eh it didnt work ima give up, sorry for bothering you

latent latch
#

you seem to have a raycast/normal problem in your video so I would fix that first

barren patio
#

how so?

latent latch
#

your cursor is bringing the mesh into the other meshes before rotation

barren patio
#

thats the offset i apply to the "ghost" object

#

its meant to offset

latent latch
#

assuming you're not childing the object or anything, it seems you just need to use world up axis and rotate it on the y

#

so start debugging values and make sure your cursor isn't interfering with it

lean sail
#

i wanna have a debug screen where I can keep track of how many poco objects exist, just to make sure they're actually getting destroyed at some point. Is this a good usecase for WeakReference? Ive never really used it before and this was something I saw popup online a bit when researching.
Im thinking of something like this https://gdl.space/jilujumuno.cs

#

Otherwise im just trying to use the memory profiler or the finalizer to check if my instances are being destroyed, which isnt fun

barren patio
#

CHAT GPT FIXED IT OMGGGG

#

im so happy

raven flare
#

dub

fickle fern
#

i need help my build and run is diffrent from my editior and i think its related to a tag problem

#

ill send a screenshot of my script

somber nacelle
#

make sure to also check the player !logs after you test a build, you may have errors in a build that you are not experiencing in the editor

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

fickle fern
somber nacelle
#

have you confirmed that by reading the log file?

fickle fern
#

there is no problems in the console when i build and run

#

just a debug.log at most

somber nacelle
#

that doesn't mean your build is not experiencing runtime exceptions. if only there were some way you could confirm whether that is the case or not

fickle fern
#

it is just not picking up the player tag and switching states

#

in the build and run

somber nacelle
#

you'll need to show the relevant !code for that

tawny elkBOT
fickle fern
#

but it is in the editor

#

ok!

somber nacelle
#

and you still need to make sure that the build does not have errors logged in the log file

fickle fern
#

im new to unity so how would i go about doing that

somber nacelle
#

because, naturally, an error would cause issues with your code like exactly what you've described

somber nacelle
fickle fern
#

i thought you meant in the console, i didnt know that there was a seperate file sorry.

somber nacelle
#

i specifically told you to check the log file

fickle fern
#

where is the log file typically

somber nacelle
#

did you not even bother reading the bot message that i just linked back to?

#

there's a convenient "Documentation" link that tells you where all of the log files are located

fickle fern
#

ok, thanks

fickle fern
#

do you know why this is happening?

fleet gorge
#

one of your prefabs might be included in a scene but is deleted

#

or your script is deleted but still applied to a gameobject

fickle fern
#

it says object not set to an isntance of an object in the debug files

#

but i cant open log since it locks my cursor

#

this is my file

plucky aurora
#

hi is there a way to automate adding textures to material?

#

i have a lot of materials that i need to add adding one by one is quite tedious

somber nacelle
fickle fern
#

thank you my glorious king

somber nacelle
#

one of the most important things you'll probably need to do is to ensure you mark the materials as dirty when you modify them (i assume, i'm not actually 100% sure if that would be necessary but it usually is when modifying assets via editor tools)

stable kayak
#

So, I can’t really do SQL locally on my machine, and would like to apply databases with a test environment on my game, any suggestions?

primal wind
#

SQLite?

knotty sun
stable kayak
soft socket
#

Would anyone know how to get the colliders to behave like they do in getting over it? where despite being in 3d,space the colliders behave as if they were 2d from the cameras POV.

knotty sun
stable kayak
knotty sun
#

Also MySQL is not as heavy on resources as SQL*Server

stable kayak
knotty sun
stable kayak
thin aurora
soft socket
#

Ill try it.

thin aurora
#

Otherwise you have a 3rd axis that is never used anyway

#

Because a 2d game also uses 3d objects. It's just all flat. Here it does actually occupy a third axis but that doesn't mean you need to apply this to the colliders

soft socket
#

Its so odd to apply a 2d collider to a 3d object but here goes.

soft socket
#

Like getting over it, I need the collision to be really accurate to what you see.

thin aurora
#

You just need to make sure the collider remains the correct orientation

gray mural
#

Hey. Does anyone have any ideas on simplifying this Coroutine ? The methods used are irrelevant.

leaden ice
chilly surge
#

Presumably delay and interval are not the same.

gray mural
#

And that's the reason

leaden ice
#

Also instead of:

    while (true)
    {
        if (!CanMove(value))
            yield break;```
why not just:
```cs
    while (CanMove(value))```
gray mural
#

Now it should be the finished version

#

Thank you!

#

I just felt like I was missing something.

chilly surge
#

I mean you could do something like:

WaitForSeconds interval = null;

while (CanMove(value))
{
    Move(value);

    yield return interval ?? new WaitForSeconds(_moveDelay);
    interval ??= new(_moveInterval);
}

The code is shorter, but is it better? I'm not sure.

gray mural
#

Also the first WaitForSeconds after the ?? can be simplified too

leaden ice
#

well you do lose the GC optimization

gray mural
leaden ice
#

If your goal is "fewest number of lines" it's good

chilly surge
#

Wdym by GC optimization?

#

This version should only allocate 2 waits, just like the original.

leaden ice
#

Reuse of this:

WaitForSeconds intervalWFS = new(_moveInterval);```
#

oh

#

you're right

#

sorry it's early

chilly surge
#

Sounds like coffee time 😄

#

But yeah if you didn't need to care about allocations, eg if you are using UniTask, it'd be so much simpler to write and understand:

var hasDelayed = false;

while (CanMove(value))
{
    Move(value);

    await UniTask.Delay(hasDelayed ? _moveInterval : _moveDelay);
    hasDelayed = true;
}
drowsy aurora
#

I have a code that sends some text to my "custom arduino controller" over serial and my arduino replies to that with 2 lines of text but somehow I can only get unity to interact with one of the lines of code (even if I disable the first line it won't interact with that second line) so I feel like it has something to do with the formatting. How can I get it to also interact with the second line?

It only replies "DitIsEenTest" while I'd also expect "Goedemorgen" (The arduino does send both)

Already simplified both codes as far as I can to exclude other errors, but I'm still a modeller and not a programmer 😅

Unity: https://hatebin.com/tgjhrcqcmi
Arduino: https://hatebin.com/icswfhrwql

chilly surge
#

(I almost feel like an async/await or UniTask salesman at this point, but truly almost every question regarding coroutines it's almost always nicer to write using those instead)

rigid island
rigid island
#

are you able to print Serial.println(receivedText)

#

make sure "TEST" is what is actually being received

drowsy aurora
#

Not sure how I would do that, can only connect to the arduino with 1 program over serial so if I'm connected with unity I can't connect to it with other software afaik.

plucky inlet
#

just print your receivedText instead of the if statement

drowsy aurora
#

oh that was already in it that was correct

plucky inlet
#

can you print if receivedText equals "TEST"?

#

oh wait, the println is on arduino site.

rigid island
#

yes the aurdino code , i was saying if they can print on display what is actually being received instead of generic logs

drowsy aurora
#

changed it to display what is being received and it is "TEST"

#

sorry been a long day and thought I changed it back to that before asking the question 😅

knotty sun
#

try

if (receivedText.subString(0,4) == "TEST")
#

also very unsure how the loop is actually looping

plucky inlet
#

For me it looks like you are always writing two lines in one serial write.

#

Thats why you always get the same result in the first line?

plucky inlet
drowsy aurora
green cypress
#

:(

rigid island
#

not a code question. also dont crosspost

green cypress
#

isnt unity code

#

what is cross post

#

sorry ill delete it

rigid island
#

posting the same question in multiple channels

green cypress
#

oh

#

sorry

rigid island
#

👍

unique trench
#

I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.

How can I find out the inverse lerp of Vector2? That is:

IF:

// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)

And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);

To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true

N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
dawn marlin
#

Hi guys, I want to show a dialog box when the app reopens, my code is as follows, but when I click the button in the dialog box, it reopens my previous window. I think it's the cause of some system calls, but I can't find the information about it, can anyone help me

thick terrace
rigid island
#

oh nvm yea its part of UnityEditor class

#

cant ctrl Z my deletion lol

rigid island
#

this class is editor only

dawn marlin
rigid island
#

alr just letting you know, wont be able to build with those classes

dawn marlin
dawn marlin
thick terrace
drowsy aurora
leaden ice
dawn marlin
#

It's just because I can't pause my Unity program

dawn marlin
#

The first one doesn't solve the problem(OnApplicationFocus runs after OnApplicationPause), the second one can

light surge
#

hello there, I have a Texture2D of the terrain heightMap and I will convert to a flatness map by using the delta rgb with the neighbors to get how flat the pixel is. My question is with my flatness Texture2D, how can I find the biggest area within a specified delta?

#

to sum up, with a texture like this how can I localize the whites spots?

dull barn
#

i am trying to make a top down shooter and I want my enemies to spawn randomly, problem is that the enemies can spawn right next to the player and damage him instantly, is there s simple way to fix this?

light surge
#

get the player position and the possible spawn point. Calculate the distance between these and if dist < min radius, doesn't spawn

vital granite
#

I need some advice setting up an if for my idle animations
It's set up currently so it can only activate while player is grounded and is not moving but issue with that setup is that if the player is only moving left to right or forward to backward there's a few seconds where the conditions are all met and plays the idle for a few frames between changing run directions when it shouldn't.
I tried solving this by making a coroutine which stores the current value of the player's inputs and then waits a few seconds to see if both variables still equal each other but then that leads to the issue of the run animation taking longer to end than it should.
Any recommendations/suggestions on something better I could try to fix it?

dull barn
light surge
dull barn
#

I get a random pos from the left side of my screen to the right for X and up and down for Y, and then I instantiate the enemy somewhere inbetween

unique trench
#

I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.

How can I find out the inverse lerp of Vector2? That is:

IF:

// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)

And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);

To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true

N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
light surge
dull barn
#

I use a Random.Range from the left side of my screen to the right side of my screen to get an X value that spawns my enemy inside of my view and same for Y

#

it basically creates a rectangle around my camera where an enemy can spawn

buoyant crane
light surge
dull barn
#

I use a float to store the randomX value, so i cant use it in the vector2.distance, can I convert the float to a position?

light surge
#

new Vector2(posX, posY)?

dull barn
light surge
#

if you need the gameobject as input, return null if failed and if you method is null, retry again. If you don't need the gameObj as out, just out a bool.

dull barn
#

what does the gray message mean?

daring plover
dull barn
#

yes

daring plover
#

for void you just do 'return'

light surge
#

your method is a void

dull barn
daring plover
dull barn
#

okay

daring plover
#

what are you trying to do

dull barn
#

holy moly it just spawned like 50 enemies

light surge
#

You got wrong

dull barn
light surge
#

Take the transform + new Vector... ) and put it in a new vector3 before the instantiate

#

then take instantiate and put inside the if

#

make your Spawn as bool Spawn

#

retrun true inside the if and add else retrun false

#

in you Update loop, reset the timer only if Spawn == true ' if(Spawn()) '

dull barn
#

2D

#

top down

light surge
#

then this will work. Try to write it and copy paste your code in the chat. I will help if it doesn't work modify.

dull barn
#

I am confused but Ill try my best

light surge
dull barn
#

okay

buoyant crane
ripe wave
light surge
#
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;



public class Shield : MonoBehaviour
{
    float timer = 2;
    Vector3 playerPos = Vector3.zero;
    float minRadius = 10;
    GameObject enemy;
    private void Update()
    {
        timer -= Time.fixedDeltaTime;
        if (timer < 0)
        {
            if (Spawn())
            {
                timer = 2;
            }
        }
    }

    bool Spawn()
    {
        Vector3 posTmp = new Vector3(Random.Range(-15f, 15f), Random.Range(-7f, 7f), 0);
        if (Vector2.Distance(posTmp, playerPos) > minRadius)
        {
            Instantiate(enemy, posTmp, Quaternion.identity);
            return true;
        } else
        {
            return false;
        }
    }
}```
light surge
rigid island
dull barn
#

thanks

light surge
rigid island
#

no need

light surge
#

why not?

rigid island
#

throwing a static variable at this problem is unecessary

#

if health is 0 script can just disable itself

light surge
#

Indeed

#

but why not use timescale = 0 to pause everything?

dusk apex
#

Do you want to pause everything or just stop spawning more enemies?

rigid island
#

I think op was trying to only disable movement of player when dead

ripe wave
rigid island
#

you could use an event from a game manager or something, this way other scripts can do something

rigid island
tawny elkBOT
rigid island
#

don't use screenshots for code

#

your vscode still doesn't seem configured for unity btw

#

did you get the Unity Extension?

ripe wave
rigid island
rigid island
#

anyway In regardss to this, a simple solution is just learning the event

light surge
#

This is another little Unity engine tutorial about how to use animation events! They can be used for all kinds of things, but in this video I show how to use animation events to sync up an effect (a particle effect or a sound, maybe) with a character's footsteps. You can use this to create little puffs of dust, or a stepping sound, or even somet...

▶ Play video
rigid island
#

a bool would working but imo polling it everyframe to be checking inside every script is iffy

rigid island
light surge
cold horizon
#

I'm having a rather annoying error pop up for my procedural generation. I'm trying to have a GameObject variable copy the "prefab" in this script but I get the mildly infuriating "Transform resides in a Prefab asset and cannot be set to prevent data corruption". not sure how to post code correctly tho

rigid island
#

if you want an inspector solution there is also UnityEvent

#

lets you link multiple scripts and methods inside inspector, same way OnClick basically works for UI Button

light surge
tawny elkBOT
misty vapor
#

Hello, I am currently attempting to make a procedural voxel terrain in unity and using the async and await keywords to multithread the process, except I get a MissingReferenceException after I stop playing the game in the editor for some reason. Any ideas as to why it would be the case?

Here's the code and the line I get the exception at is commented below.

private async void GenerateMeshForChunk(int i, int j, float[,] noiseMap)
{
    var result = await Task.Run(() =>
    {
        MeshData meshData = new MeshData();

        for (int y = 0; y < chunk_height; y++)
        {
            for (int z = 0; z < chunk_size; z++)
            {
                for (int x = 0; x < chunk_size; x++)
                {
                    //Debug.Log(new Vector3Int(x + i * chunk_size, y, z + j * chunk_size));
                    List<Vector3> faceVertices = GetCubeVisibleFaces(new Vector3Int(x, y, z), new Vector3Int(i * chunk_size, 0, j * chunk_size), ref noiseMap);

                    for (int k = 0; k < faceVertices.Count; k++)
                    {
                        meshData.vertices.Add(faceVertices[k]);
                    }

                }
            }
        }

        for (int k = 0; k < meshData.vertices.Count; k++)
        {
            meshData.indices.Add(k);
        }

        return meshData;
    });

    chunks[i * num_chunks + j].transform.position = new Vector3((i * chunk_size), 0.0f, (j * chunk_size)); //I GET THE ERROR ON THIS LINE!

    chunkFilters[i * num_chunks + j].mesh.Clear();
 
    chunkFilters[i * num_chunks + j].mesh.vertices = result.vertices.ToArray();
    chunkFilters[i * num_chunks + j].mesh.triangles = result.indices.ToArray();

    chunkFilters[i * num_chunks + j].mesh.RecalculateNormals();
}
misty vapor
light surge
#

Do you destroy your chunk at some point?

misty vapor
#

no, I just stop the game and I get that error after stopping it for some reason.

lean sail
fervent furnace
#

stopping playmode will destroy all the gameobjects

misty vapor
lean sail
#

No, this means your code is still running after play mode

#

You need either to rethink about using async or use like a cancellation token

misty vapor
#

oh... is there a way I can stop the async after I stop playing?

light surge
#

Oh, I didn't see async. Never used it, what is async for?

misty vapor
#

multithreading

fervent furnace
#

syntax sugar for not writing a state machine that handles non-blocking operation

misty vapor
#

is there a way I can stop it after I stop playing?

fervent furnace
#

You need either to rethink about using async or use like a cancellation token by bawsi

misty vapor
#

what is a cancellation token?

light surge
lean sail
light surge
misty vapor
lean sail
#

Though I find it odd you're suggesting tutorials on it when you just learned what async is...
Theres no way you read through all of that

light surge
chilly surge
#

Can also use UniTask, I think UniTask handles the editor play mode cancellation for you.

light surge
#

I have my own question: I have a 2D texture like this one. What would be the best way to find the middle of the biggest area?

#

Doesn't need to be with Texture2D, I have the same data in a float matrix

misty vapor
#

I think you can do some version of heuristic matching. Perhaps fill the white pixels with two values, distance from black and number of whites surrounding the pixel.

#

or just smudge or blur the texture, the whitest area in the end is the winner?

light surge
misty vapor
fervent furnace
#

blurring should work as long as the kernel size is right but now the problem becomes how to get the correct kernel size

cold horizon
#

i have this that was procedurally generated. How do i get rid of the bar-code look on certain parts of it?

#

I also want to make it look a bit mor natural, any suggestions?

#

nvm i got it it was the model scale

gray mural
#

I have a player, snake, which consists of the blocks, which all have a BoxCollider2D on them. The snake's length can be changed, which means it can have a large amount of blocks. Moving a snake around translates the 1st block on 1 unit to the desired direction, and the other blocks' positions are assigned to their previous one. Every block is 1x1 in Unity coordinates, and its position should always stay inted at the end of the "continuous" movement.
What would be the best way to apply the gravity to the snake to not decrease the performance too much? Using the Rigidbody2D with the CompositeCollider2D doesn't work as desired, as the collisions with the ground blocks aren't calculated precisely and the blocks' positions aren't inted after the application of the gravity.

leaden ice
#

unless you're doing some physics-based twist on it

gray mural
# leaden ice I would probably not be using physics for a Snake game at all

Right, that's what I thought too. I wanted to use a while to create a loop for every single block and check whether it has a ground block 1, 2, 3 etc. units under it. It works perfectly when the distance between the ground and the number of blocks aren't too big, but once they get, the performance is going to decrease significantly.

#

Perhaps, there is any efficient method, which allows to check for the nearest Collider2D under the CompositeCollider2D.

#

But it's also so that the distance between the snake's block and the ground block should be considered.

#

Even when the 2nd block is under the 10th block, the smallest distance between the block and the ground block should be chosen

gray mural
#

It's also important to break the process when the Collider at the distance 1 is found, as this is when the snake is staying on the ground

#

And every block's collider should cover the entire 1x1 space

unique trench
#

I'm sure this should be an easy math question, but I've been fighting this for hours and can't figure it out; tried googling and AI too.

How can I find out the inverse lerp of Vector2? That is:

IF:

// A is normalized
// B is normalized
// A and B are NOT colinear
Vector2 N = Vector2.Lerp(A, B, pct)

And we have A, B, and pct, we need to implement method ?
float pct = InverseLerp2(A, B, N);

To clarify, I don't need the exact pct that was used - but rather any PCT. The following should be true

N == Vector2.Lerp(A, B, InverseLerp2(A, B, N)) // assume an equal is done using floating point estimation/threshold, not an exact equal
mossy snow
worthy tinsel
#

Proof:

N = A + pct * (B - A) = A + (N - A) / (B - A) * (B - A) = A + N - A = N;
soft shard
#

Why can I not cast an object type as a int to a function that takes a int param? Why do I need to first cast it to a float?

public void SomeNetworkFunc(object[] data)
{
SomeLocalFunc((int)((float)data[1])); //works without issues at runtime
//instead of simply...
SomeLocalFunc((int)data[1])); //causes "cast is not valid" at runtime
}

public void SomeLocalFunc(int value) { ... }

If its an object, shouldnt I be able to cast data to a int? Even as a float, shouldnt data be able to be cast to an int without the double-cast? Is there maybe a better way I could handle this to not need the double cast? (nothing wrong performance wise in my game with it and its not called very often on the network, I just think it looks ugly and seems like a extra step forced on by my approach maybe)

knotty sun
#
        object[] data = new object[10];
        int i = 0;
        int? x = data[i] as int?;
#

the reason you can do object -> float is that float has NAN for invalid values int does not have that

#

so using int? will get around that

soft shard
#

Ah interesting, thanks for explaining that, I dont think ive ever used ? on a variable type, ill try it out

knotty sun
#

basically it makes value types nullable

#

I like for this. bool? - true, false, maybe

heady iris
#

true, false, file not found

#

interesting -- I didn't know float could produce NaN for an invalid cast

sonic holly
#

hey guys! quick question. what would be the most efficient method of spawning objects in a procedural terrain generator?

tall scroll
#

I saw something about how structs don't get collected properly in the editor and so when playing in the editor the struct's data won't "reset" until the scene is fully reloaded. Is that true or am I mixing it up with another thingg

leaden ice
#

Or what that has to do with structs

tall scroll
#

idk I just glimpsed at the convo but something about how if you change the data in play mode it will stay like that even when you stop playing, which isn't the usual behaviour. I may be confusing it with scriptableobjects though I'm really not sure

leaden ice
sonic holly
leaden ice
#

You'd have to be comparing it with something to make a statement like that

knotty sun
sonic holly
#

mm, got it. so Instantiating with static batching is an effective way to spawn things?

knotty sun
#

oh, unless you include new GameObject(), of course

leaden ice
#

If you're willing to step outside GameObjects you can do other things

fickle moth
#

Does anyone know how to disable these warnings?

#

Nevermind i figured it out

twilit scaffold
#

can you build Windows IL2CPP on Linux? if not i have to reload in Windows. I despise windows.

west lotus
latent latch
#

Any resources for a SFX singleton manager? One feature I've yet to really touch in my projects

#

Am I looking at pooling audio clips or is it like a single component with callbacks

somber nacelle
#

i imagine that pooling would be more performant than that. i haven't really done much testing with that myself but i did make an audio source pool that basically does that. It's just a singleton with an object pool that will enable an AudioSource object, move it to the point I tell it to play at, then start playing the sound and returns it to the pool when it is done

latent latch
#

oh man do I love object pooling

wild vigil
#

does anyone have a good script for an android flycam or freecam? I just want to move around with touch controls.

calm bobcat
somber nacelle
#

don't crosspost

vernal current
#

Does anyone know why my shader render only in my left eye on the vr?

ripe wave
#

!code

tawny elkBOT
subtle path
#

so im confused by trying to combine two loops

i have a level preview that is supposed to populate each button with one level. all it does is change the sprite and the text for now.

but i cannot get it to work. it always takes the last entry of the levels (in this case level 3).

what should happen is ofc, that the first button is level 1, the second button level 2 and so on.

here is the code thats driving me nuts:

     //runs through each buttons
     foreach (var button in buttonImageText)
     {
         //checks if sprite was overwritten
         if(button.Key.overrideSprite == true){return;}

         button.Value.text = "Empty";
         //runns through each level
         foreach (var level in levelSpriteList)
         {                                           
             //SHOULD: checks if the button sprite is equal to a level sprite
             if(button.Key.name != level.name)
             {
                 button.Key.overrideSprite = level;
                 Debug.Log("amount of sprite calls");
             }
             else
             { button.Key.overrideSprite = null;}

             //SHOULD: checks if button text already has level name
             if (button.Value.text == level.name) { return; }

             if (button.Value.text != level.name)
             {
                 button.Value.text = level.name;
                 Debug.Log("amount of text calls");
             }
                   
         }
paper flame
#

Anyone ever implemented EAC to their game?

knotty sun
subtle path
knotty sun
subtle path
#

yeah but then i guess my question is.. how do i make it so it sets the correct name for each button only once

knotty sun
#

totally rethink your logic and learn to read code

ancient magnet
#

Hey, whats more performant, vector3.distance vs sqrMagnitute? I'm using it to check if I should execute logic based on if an object is not close enough to its default position.

    private void Update()
    {
        float sqrDistance = (slideHandle.transform.localPosition - slideHandle.ForwardPosition).sqrMagnitude;
        if (sqrDistance > positionTolerance * positionTolerance)
        {
            Debug.Log("executing");
        }

subtle path
knotty sun
#

and use a for loop not foreach

subtle path
#

i already did try that, but i need to get a ref on each button somehow

knotty sun
#

yes, use the indexer from the for to get the button corrsponding to the level

prisma flower
#

can anyone help me to write code for my UI design I don't know too much about script but I write it for my collage project

vagrant blade
#

Nobody is going to do your homework for you. You can !learn how to use Unity.

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

prisma flower
#

I have code and logic I need decimation link for structure assign I lacking in sytax

vagrant blade
#

What does that even mean?

prisma flower
#

I need some documentation link of C# & unity

#

specilly for stucture and file i/o

knotty sun
#

what do you think the link to unity Learn is?

prisma flower
#

yeah but I can find I my English as you see not good

knotty sun
prisma flower
#

oh thanks

subtle path
#

the solution was 2 lines of code in a for loop...

hasty canopy
leaden yoke
tall scroll
tall scroll
leaden yoke
tall scroll
tall scroll
#

the way it's animated could be causing it

tall scroll
#

so one small thing is that iirc you don't multiply mouse movement by deltatime

#

but that's not causing the issue that's just something to know

#

otherwise code looks fairly sensible so I'm going to assume it's probably something to do with the animator

#

if I'm misunderstanding what the issue is though, it could well be input handling or the deltatime thing

light surge
light surge
light surge
# leaden yoke how do I stop it?

2 way: 1- remove camera from the spine and put directly on Ch15_nonPBR with the height offset. 2- make a script to restrict camera rotation.

light surge
#

Change the camera parent

leaden yoke
light surge
wintry crescent
#

I'm on linux (EndeavourOS, X11, KDE, everything up to date)
I have done every step on https://code.visualstudio.com/docs/other/unity, including ensuring the Visual Studio package is up to date
But I still do not have code completion, neither for my own classes, nor for unity stuff. What could be the issue?

chilly surge
wintry crescent
leaden yoke
chilly surge
wintry crescent
wintry crescent
light surge
leaden yoke
chilly surge
light surge
#
float clampedXAngle = ClampAngle(currentRotation.y, minAngle, maxAngle);

        // Apply the clamped pitch angle
        currentRotation.y = clampedXAngle;

        // Update the camera rotation
        cameraTransform.localEulerAngles = currentRotation;```
light surge
leaden yoke
wintry crescent
light surge
chilly surge
leaden yoke
wintry crescent
light surge
# leaden yoke

take the Ch15_nonPBR world Y.angle and feed it to the word Yrotaion of the camra

#

in this

light surge
#

add few lines that get the ch15_ononPBR Yrotatation in euleur angle and put it in the world Y rotation of the camera.

light surge
# leaden yoke its 0

I know, but you need to do this everyframe, do it with c# code and the rotation you see is local rotation.

light surge
# leaden yoke its 0

add this code at last of code in CamMovements(): csharp camera.transform.rotation.eulerAngle = new Vector3(camera.transform.rotation.eulerAngle.x , RootGameObject.transform.rotation.eulerAngle.y , camera.transform.rotation.eulerAngle.z);

light surge
light surge
leaden yoke
leaden yoke
light surge
leaden yoke
light surge
#

is the rotation still here?

leaden yoke
#

this is soo dumb how the hell do I fix this. I followed a youtube tutorial and the guy didn't have the same problems as me. I literally copied what ever he did

light surge
leaden yoke
wide mural
#

hello, i am trying to use unity AR functions but I cannot figure out how to grab the texture of an ARTrackedImage

I found this
Texture2D referenceTexture = trackedImage.referenceImage.texture;

from Unity Doc but it doesnt seem to work though since the it's null
I know i am tracking an image because if i do this:

            {
                Debug.Log("Tracking image: " + trackedImage.referenceImage.name);
            }```
it prints out the image's ref name

any clue?
pastel patio
#

Does anyone have experience with MessagePack?

#

I've been trying to get it working for hours on end...

#

Now the issue is that the GeneratedResolver.cs can't find my SavedObject and StructureData structs

#

I still don't get it, nor can I find them manually, they aren't in a namespace per se

#

MessagePackCompiler's generated code is trying to reference them via global::SavedObject and stuff...

wintry crescent
#

Can Vector2.normalized ever return 0,0?

knotty sun
#

no because if normalized it must have a magnitude of 1

heady iris
#

I believe it returns a zero-vector if you give it a zero-vector

#

indeed

knotty sun
#

being pedantic, it's not 'returning 0,0 it's returning an invalid input

pastel patio
heady iris
#

it explicitly returns a zero vector if the input is too small to normalize

#

i am not sure if that includes very very short vectors, or if it only includes the zero vector

#
    //
    // Summary:
    //     Makes this vector have a magnitude of 1.
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Normalize()
    {
        float num = magnitude;
        if (num > 1E-05f)
        {
            this /= num;
        }
        else
        {
            this = zero;
        }
    }
knotty sun
#

it should normalize magnitude < 1

pastel patio
#

It seems to be essentially isolated from the rest of my project or something, any idea how this could happen?

heady iris
#

well, there's my question answered!

heady iris
#

Unity needs to see it so that it can create a .csproj file (or add information to an existing .csproj file)

candid elm
#

who else hates async programming

chilly surge
#

Unfortunately, the world is async 😄

simple egret
#

Async is great, it's just that Unity never used it so there's not many places where it's available

light surge
#

UNREALTED to my previous message:

Question: I'm using render Textures to create my impostors. Is it the right way or it's wrong ? Just to be sure before I do every angle (Sphere).

#

Don't need to say to add Fade between angles. I will.

latent latch
#

what's an imposter

#

oh is that some sprites with different frames

#

id' just use the sprite/texture atlas

light surge
#

From a article: An Impostor

Impostors is a technique used for a background of the game environment to fake 3D objects by using its texture maps and transfer them onto images or billboards.

This way, the number of polygons is much fewer which leads to spending less time to render a scene but the quality of the environment remains almost the same. The key point of this technique is to replace those 3D objects that aren’t in the main focus of the player’s view so he won’t spot the difference.

#

To sum up, It's a way to fake a 3D gameobject with a 2D sprite. The cherry tree on the far right is 3D. The two in middle are 2D.

latent latch
#

no clue the overhead of using multiple cameras like that even if you're just capturing a single render, so something to profile. Otherwise cache yourself the textures and stick em in some dict with texture coordinates imo

nimble cloud
#

hi im trying to learn how to have items in my enviroment with scriptable objects attached to store the items data. i have got the scriptable object file working but struggling to add the data to a game object that my player can pick up. anyone able to direct me to some resources that can explain how to do this.

knotty sun
simple egret
nimble cloud
#

ok so done that but its not loading the prefab for the item into the scene. im guessing im missing something else

#

i have loaded it onto a empty object. should i be adding it to a prefab of the game object even though the SO has a gameobject field?

#

what im trying to do is have items that can be picked up and scrapped so i am trying to use SO to hold the data on the materials for the item

knotty sun
#

you should have some thing like
Project
SO Script
-- SO Asset
MB Script
-- Field of same type as SO script
Hierarchy
GameObject
-- Instance of MB script
-- Reference to SO Asset

nimble cloud
#

yea dont have anything like that i have a prefabs folder for the stuff i made in blender to learn this stuff and a scripts folder for the SO and other scripts

#

what does MB stand for ?

knotty sun
#

Monobehaviour

nimble cloud
#

ok

knotty sun
#

The GameObject can also be a prefab in the project

nimble cloud
#

right but in my SO i have set a public GameOject field to set the prefab to but the prefab is not being displayed on the empty game object

knotty sun
#

you are going to have to show your inspectors of the objects

nimble cloud
#

am i right in thinking i just need to setup the object with the SO then make a prefab of that game object in the Hierarchy to add multiple of the same item with the SO

knotty sun
#

if I understand you correctly, yes

nimble cloud
#

ah ok so thats good then

candid elm
#

Would you guys recommend me to switch from dotween to leantween

versed spade
#

Was hoping to get some help with getting UI elements that display what planet is what in the solar system of my game. Currently I managed to get these elements to orbit but they are not alligning themselves at the center of my camera.

Follow Script Code: https://gdl.space/yuxezogeqo.cpp

nimble cloud
#

i thought having the prefab in the SO would mean that i had to just add the script to a empty game object and it would display the object listed

knotty sun
#

what script?

nimble cloud
#

ok its working thanks for the help @knotty sun

versed spade
quaint crypt
#

i want to limit the movement of a recttransform to not overflow below the screen at all. so if i detect overflow, i just change the pivot to (0, 0), and the anchorMin to (0, 0) and the anchorMax to (0, 0), and position the anchoredPosition.y to 0. works well. but then i want to set the pivot / anchors back to their original values (0, 1) for pivot, and (0, 1) for anchors, but it messes up the positioning. even if i remember the localPosition before setting back the anchors and set it to that after changing them. any ideas why?

#

in the last line, i accidently set the world pos, but even setting the localPosition still has the same issue

feral forge
#

Hi, I was wondering where do I go for help, as I'm trying to create a death floor, which works but it appears im clipping through objects on spawn

-Attempted elevating the characters/player
-Considered setting the movement speed to 0 but not sure how to call to another file/class
-changed the distance to reach the death floor

Using Scripts to create the deathfloor/checkpoint based system