#archived-code-general

1 messages · Page 360 of 1

knotty sun
#

reverse for loop

static matrix
#

ohhh yeah
makes sense

spring creek
#

Does that really need to be explained? Because it is awful, nausea inducing, blurry, doesn't show everything, and against server rules.

glad dew
#

@static matrix also using lambdas generates garbage.

unreal herald
#

hey can anyone help me?,
i made a death popup thing and instead of only popping up when the player dies, it does it right after i click play/run

knotty sun
#

Are you going to post some !code or do we just have to guess at what you have done?

tawny elkBOT
unreal herald
#

oh srry

#

this is the gameovermanager code

#

idk how to make it in a box

knotty sun
#

So you just totally ignored the bot message

unreal herald
#

whats backquotes

#

oh

#
using UnityEngine.SceneManagement;

public class GameOverManager : MonoBehaviour
{
    public void RestartGame()
    {
        Time.timeScale = 1f;  // Unfreeze the game
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);  // Reload the current scene
    }

    public void QuitToMainMenu()
    {
        Time.timeScale = 1f;  // Unfreeze the game
        SceneManager.LoadScene("Main Menu");  // Load the main menu scene (replace with your actual main menu scene name)
    }
}
#

i cant send the other script

#

too big

static matrix
#

to be extra fancy, add cs after the first three backticks

static matrix
unreal herald
knotty sun
#

Debug your code, specifically the TakeDamage method

unreal herald
#

is the problem that i start with 0 health or something?

#

i did set the currentHealth to MaxHealth

knotty sun
#

obviously

unreal herald
#
    public int currentHealth;```
knotty sun
#

irrelevant, look at the values in the inspector

unreal herald
#

wat

naive swallow
unreal herald
#

wdym on the inspector

knotty sun
#

omg

naive swallow
#

The window named "inspector"

unreal herald
#

ik about the window

naive swallow
#

So look at it

unreal herald
#

but where the hell would maxHealth be

#

in the inspector

naive swallow
#

and see what maxHealth is set to

naive swallow
unreal herald
#

oh

#

thank you all, i love you

rigid island
unreal herald
#

im so dumb 😭

#

it fixed it perfectly, even the restart button works 🎆

static matrix
#

im just joking
but it can feel like a gut punch when you think you are good at coding 😔

knotty sun
rigid island
#

#code-preschool

static matrix
#

#blockcode

odd void
#

So i came across the IEnumerator and i wonder what it is? i think its a return type thats executes your code but u cant tell it to wait a few seconds until he executed your code again? right?

cold parrot
#

Unity can automatically do that for you ‚one step per frame‘ —> Coroutine

weak spruce
weak spruce
somber tapir
knotty sun
rigid island
weak spruce
knotty sun
#

which is even more reason not to load EVERY FRAME

weak spruce
#

if i load it on start inventory doesent update

somber tapir
weak spruce
#

List items is called with inventory Button

somber tapir
# weak spruce List items is called with inventory Button

ok, what it happening is:
You add a sheep ->
ListItems() is getting called ->
You loop through all the items, starting with the first item (normal sheep) ->
The if statement gets triggered because Items.Count is now increased by 1 ->
You create a new sheep display ->
You take the data from the first item, which is a normal sheep

#

You should also have your item display be it's own class, something like this:

public class ItemDisplay : MonoBehaviour
{
    [SerializeField] private TMP_Text itemName;
    [SerializeField] private TMP_Text rarityText;
    [SerializeField] private Image icon;

    [SerializeField] private Color rareColor;
    // ...

    public void DisplayItem(Item item)
    {
        itemName = item.itemName;
        // ...
    }
}

------------ In your InventoryManager -----

public ItemDisplay InventoryItem; // replaced 'GameObject' with 'ItemDisplay'

public void ListItems()
{
    // ...
    ItemDisplay display = Instantiate(InventoryItem, ItemContent);
    display.DisplayItem(item);
}```
compact fog
#

Basic question: I have a box collider 2d on my enemy as the main collider. I also have a circle collider 2d set to isTrigger to act as a sensor to know what objects are close. On the enemy i have it set to the enemies layer which i mask for on my players raycast to determine if I hit an enemy. The issue I am having is that the circle collider is registering as hit which is unintended. I tried setting the Layer Overrides to ignore raycast (and everything) but that doesn't seem to function like i thought it would and is still captured by the raycast.

somber tapir
compact fog
compact fog
#

Was hoping I was misunderstanding the layer overrides field and they would solve my issue

#

and just checked the docs (which i should of done first my b) where it clearly states layer overrides are between colliders not raycast and collider.

green wharf
#

im using object pool but i cant select an object based on percentage from object pool, should i create more than one object pool for this??

leaden ice
#

Which you seem to have realized

wide terrace
green wharf
#

i realize im not clear enough, sorry for my bad english let me to use gpt

soft shard
green wharf
#

I am adding coins with different values to an object pool, but the more valuable coins should appear less frequently. When I use the pool.Get() method, it's not working as I want it to

green wharf
#

after calling the coins from the object pool, i was thinking of assigning new scriptable objects to them but they also have different colors or meshes

green wharf
#

should i use dictionary

queen saffron
#

what is the best UI i can use for preserving presents and put icons that represents each present on them? (plz don't tell me to put bunch of buttons xD)

#

like a vertcial bar that contain presents name or icons (i don't mind)

wide terrace
# green wharf should i use dictionary

Probably something else, yeah... It sounds like you want to randomly draw an item from a collection, where each item type has a different probability of being chosen. That's not something which an object pool is really meant to do or handle.

You might try researching "weighted collections" or "loot tables"

green wharf
#

thanks

simple void
#

you're gonna need to provide more info than that, but on a hunch, you have to actually update your position. tform.position.x = xvalue

simple topaz
#

thanks

royal wigeon
#

Where can I find people who want to team up with me to make games.

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

royal wigeon
#

Thanks

#

Dang bro it's impossible to find someone to work with me...

soft shard
soft shard
royal wigeon
#

I just want to work with someone on games for fun, a hobby, someone who shares a interest in making games.

soft shard
vital atlas
#

So I've been working for a bit on a concept game using the visual scripting, not looking for help with that i'm at a point where i need to restart, so i'm reevaluating if it's worth using it or not

it seems like certain things are pretty convienient, but it also seems like other things are very difficult to do when they would be simple in code.

I noticed most Unity examples i've seen using a lot of regular scripting instead, do y'all have opinions on that?

tame thunder
somber nacelle
#

well this channel is specifically a code channel, so the prevailing preference here would be "code"

tame thunder
#

I can have an ide with 25,000 lines of code open without a hitch
Even a fairly basic script graph uses a load of performance in the editor

vital atlas
spring creek
tame thunder
spring creek
spring creek
somber nacelle
vital atlas
#

All of these are pretty good points, yeah.

void basalt
#

another drawback of visual scripting is that you aren't learning any real world skills... like nobodies going to hire you for that

vital atlas
#

i do like being able to see what nodes are active live while testing, but yeah i can probably more or less do that in the debugger with regular script

tame thunder
#

I just mainly find it's really really performance heavy

#

At least in the editor, I got no clue about runtime

void basalt
#

I can't imagine the headache that comes with trying to optimize visual scripting on the user-developer end.

vital atlas
#

at least from when i was testing a very very simple project, it was much faster when not viewing the editor

#

but idk how it would compare to regular script

#

i kindof imagine it must be compiled to regular script eventually...

tame thunder
#

Yea I think I've read it's not compiled to something manageable by a human though

#

For VSG/Bolt at least

#

Actually does it have its own method for saving and loading or are you still making a serializer anyway

mild coyote
#

I'm not sure if this should go to animation or here, but since it's mostly code I'll just post it here
So, I want to enable an animator, sample the animated positions, and disable the animator afterward.

animator.enabled = true;
animator.Play("Die");
animator.SetBool("Die", true);
for(int i = 0;i < bodyParts.Count;i++)
{
  bodyPartEndRotations.Add(bodyParts[i].rotation);
  bodyPartEndPositions.Add(bodyParts[i].position);
}
animator.enabled = false;

but it always returns default pose (not the T or A pose, but the pose when not in playing mode)
The code above is inside LateUpdate function. Is there something I missed?
Or maybe the animation transform only available on the nextframe after it's enabled?

broken light
#

if im in prefab mode what is the general approach to stop OnEnable registering my object to my manager?

#

i need it to work in scene and in run time but not when im in the prefab editor

opal ivy
#

Drew up a diagram for something I am wanting to achieve, I was wondering what the most efficient route to make this possible for a 2D platformer so that I can eliminate the need for load screens and make exploring seamless. If anyone more experienced with 2D games could give me some pointers that would be appreciated!

#

More specifically, I want it to be kind of like a "Layer" where the level you were just on fades out going twoard the screen as you enter the new room area

silent tapir
#

My question is that when I put down items into a backpack, then pickup the backpack out of its slot (triggering the save function in StorageData.cs), and then put the backpack into its slot again (triggering the load function in StorageData.cs), why does it load the items but I can't pick them up, when I usually can pick them up without involving backpacks. I will tell you that I think it has to do something with the inventoryItemSlot array. But I need help badly please.

leaden ice
#

If they enter, you can activate the scene. You can also unload it if/when they step far away from the door and don't enter it

cosmic rain
tawny elkBOT
cosmic rain
#

And then also share whatever debugging steps you've taken so far.

silent tapir
#

I've debug logged that:

public InventoryItem PickUpItem(int x, int y)
    { 
        Debug.Log("x: " + x + "," + "y: " + y);
        Debug.Log("2nd: " + inventoryItemSlot[x, y]);
        InventoryItem toReturn = inventoryItemSlot[x, y];

        if (toReturn == null) return null;
        CleanGridReference(toReturn);

        if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);

        return toReturn;
    }``` the debug logs are not both validly logging, only the first one :/ so toReturn always logs null
#

even though I am setting it in StorageData.cs

cosmic rain
#

Meaning that the InventoryItemSlot element that you're trying to access contains null. So you just need to debug whenever the array is modified.

#

To see when it's being set to null and why.

silent tapir
#

ive logged everything and its not adding up but I will go thru one more time

silent tapir
# cosmic rain Meaning that the InventoryItemSlot element that you're trying to access contains...

I mean this is logging correctly here,

public void LoadGrid(ItemGrid grid)
    {
        string path = Path.Combine(Application.persistentDataPath, "gridState.json");

        if (!File.Exists(path)) return;

        string json = File.ReadAllText(path);

        if (string.IsNullOrEmpty(json)) return;

        GridState state = JsonUtility.FromJson<GridState>(json);

        grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];

        Debug.Log(grid.inventoryItemSlot);

        foreach (ItemState itemState in state.items)
        {
            if (state.items.Count == 0) return;

            InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
            inventoryItem.Set(itemState.itemData);

            RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();

            Vector2 newPosition = new Vector2(
                itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
                -(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
            );

            rectTransform.anchoredPosition = newPosition;

            inventoryItem.onGridPositionX = itemState.posX;
            inventoryItem.onGridPositionY = itemState.posY;

            rectTransform.sizeDelta /= rootCanvas.scaleFactor;
        }
    }```
cosmic rain
silent tapir
cosmic rain
#

This creates a new array. It doesn't assign anything to it.

silent tapir
#

oh you're saying I need to do like:

in the foreach, grid.inventoryItemSlot[x,y] = the inventoryItem

#

or in a for loop or whatever

cosmic rain
silent tapir
#

I need to actually populate it with items from the state save

#

is that what you're saying? ^

cosmic rain
silent tapir
#

Okay I compeltely just dodged that lol thanks let me try that

silent tapir
# cosmic rain Yes. That would be an assignment to an element of the array.
public void LoadGrid(ItemGrid grid)
    {
        string path = Path.Combine(Application.persistentDataPath, "gridState.json");

        if (!File.Exists(path)) return;

        string json = File.ReadAllText(path);

        if (string.IsNullOrEmpty(json)) return;

        GridState state = JsonUtility.FromJson<GridState>(json);

        grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];

        foreach (ItemState itemState in state.items)
        {
            if (state.items.Count == 0) return;

            InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
            inventoryItem.Set(itemState.itemData);

            RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();

            Vector2 newPosition = new Vector2(
                itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
                -(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
            );

            rectTransform.anchoredPosition = newPosition;

            inventoryItem.onGridPositionX = itemState.posX;
            inventoryItem.onGridPositionY = itemState.posY;

            rectTransform.sizeDelta /= rootCanvas.scaleFactor;

            grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
        }
    }``` how ain't this workin?
cosmic rain
#

You'll need to define "not working"

silent tapir
#

I am quite literally populating the array? but its not carrying over to this line (where it says 2nd:

public InventoryItem PickUpItem(int x, int y)
    { 
        Debug.Log("x: " + x + "," + "y: " + y);
        Debug.Log("2nd: " + inventoryItemSlot[x, y]);
        InventoryItem toReturn = inventoryItemSlot[x, y];

        if (toReturn == null) return null;
        CleanGridReference(toReturn);

        if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);

        return toReturn;
    }```
#

sry i was typing that

cosmic rain
#

Then nothing is assigned to that array at that index.

#

Debug what is getting assigned at what index.

silent tapir
#

Debug.Log(itemState.posX + ", " + itemState.posY);

#

got it testing rn

cosmic rain
#

This just debugs the indices. Not what is assigned.

silent tapir
cosmic rain
silent tapir
#

alr i will

cosmic rain
#

These logs tell you literally nothing aside from the fact that these indices are used somewhere.

silent tapir
cosmic rain
#

No. Log it all in one message together with the indices

#

"Assigning at x, y: item"

silent tapir
cosmic rain
silent tapir
cosmic rain
#

Where's the second log then?

silent tapir
#

the first one logged an identical position to that in the PickUpItem(), and the 2nd is logging the name of the newly loaded item.

silent tapir
cosmic rain
#

Ok, and what does it log when trying to access the item at that position?

#

Share the updated code.

silent tapir
#
public InventoryItem PickUpItem(int x, int y)
    { 
        Debug.Log("x: " + x + "," + "y: " + y);
        Debug.Log("2nd: " + inventoryItemSlot[x, y]);
        InventoryItem toReturn = inventoryItemSlot[x, y];

        if (toReturn == null) return null;
        CleanGridReference(toReturn);

        if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);

        return toReturn;
    }```


```cs
public void LoadGrid(ItemGrid grid)
    {
        string path = Path.Combine(Application.persistentDataPath, "gridState.json");

        if (!File.Exists(path)) return;

        string json = File.ReadAllText(path);

        if (string.IsNullOrEmpty(json)) return;

        GridState state = JsonUtility.FromJson<GridState>(json);

        grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];

        foreach (ItemState itemState in state.items)
        {
            if (state.items.Count == 0) return;

            InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
            inventoryItem.Set(itemState.itemData);

            RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();

            Vector2 newPosition = new Vector2(
                itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
                -(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
            );

            rectTransform.anchoredPosition = newPosition;

            inventoryItem.onGridPositionX = itemState.posX;
            inventoryItem.onGridPositionY = itemState.posY;

            rectTransform.sizeDelta /= rootCanvas.scaleFactor;

            grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
            Debug.Log(itemState.posX + ", " + itemState.posY);
            Debug.Log(inventoryItem);
        }
    }```
#

the log with "2nd" in it is logging nothing

cosmic rain
silent tapir
#

hmm I will log the grid names

#

and give the new grid a random number for a name on its creation

cosmic rain
silent tapir
#

alrighty

silent tapir
# cosmic rain Pass the object as the second parameter to debug.log. Then you can click the mes...
public InventoryItem PickUpItem(int x, int y)
    { 
        Debug.Log("x: " + x + "," + "y: " + y);
        Debug.Log("2nd: " + inventoryItemSlot[x, y]);
        Debug.Log(transform.name);
        InventoryItem toReturn = inventoryItemSlot[x, y];

        if (toReturn == null) return null;
        CleanGridReference(toReturn);

        if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);

        return toReturn;
    }```

```cs
public void LoadGrid(ItemGrid grid)
    {
        string path = Path.Combine(Application.persistentDataPath, "gridState.json");

        if (!File.Exists(path)) return;

        string json = File.ReadAllText(path);

        if (string.IsNullOrEmpty(json)) return;

        GridState state = JsonUtility.FromJson<GridState>(json);

        grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];

        foreach (ItemState itemState in state.items)
        {
            if (state.items.Count == 0) return;

            InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
            inventoryItem.Set(itemState.itemData);

            RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();

            Vector2 newPosition = new Vector2(
                itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
                -(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
            );

            rectTransform.anchoredPosition = newPosition;

            inventoryItem.onGridPositionX = itemState.posX;
            inventoryItem.onGridPositionY = itemState.posY;

            rectTransform.sizeDelta /= rootCanvas.scaleFactor;

            grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
            Debug.Log(itemState.posX + ", " + itemState.posY + grid.name);
        }
    }``` like this?
cosmic rain
#

Debug.Log(text, objectReference);

silent tapir
#

@cosmic rain .......

#
public InventoryItem PickUpItem(int x, int y)
    { 
        Debug.Log("x: " + x + "," + "y: " + y);
        Debug.Log("2nd: " + inventoryItemSlot[x, y]);
        Debug.Log(transform.name);
        InventoryItem toReturn = inventoryItemSlot[x, y];

        if (toReturn == null) return null;
        CleanGridReference(toReturn);

        if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);

        return toReturn;
    }``` the third log, umm, logged a different name than the one in the Load method lol
cosmic rain
#

Well, then it's a different object

#

I bet that it references the prefab, instead of the object in the scene.

silent tapir
#

where

cosmic rain
#

Wherever you reference it. Probably in the inspector..?

#

Wherever you're passing it to the load method.

silent tapir
cosmic rain
silent tapir
#

from AddGrid:

GameObject newGrid = Instantiate(itemGridPrefab, GameObject.Find("StorageGrids").transform);```
and ```cs
return newGrid.GetComponent<ItemGrid>();```
cosmic rain
silent tapir
cosmic rain
#

And what name was printed in the pick up method?

silent tapir
#

which was just "Backpack"

cosmic rain
#

..?

#

Is it an ItemGrid object as well?

silent tapir
#

yes

cosmic rain
#

I feel like I really don't understand your setup anymore.

silent tapir
#

here

cosmic rain
#

Which one do you want to pick the item from then?

silent tapir
#

when I click the Ak-47 it calls pickupitem from the the backpack grid (#1) instead of tthe grid the ak is in (#2)

#

i just realized that

cosmic rain
#

Great. Then I guess the issue is solved.

silent tapir
cosmic rain
silent tapir
#

alr

silent tapir
#

however selectedItemGrid is logging as the one I ACTUALLY clicked on

cosmic rain
silent tapir
#

selectedItemGrid?

silent tapir
cosmic rain
#

Oh, so that's the correct reference?

#

Then the one Load is called on is not correct.

silent tapir
cosmic rain
#

Make sure you back up your assumptions with proper debugging.

silent tapir
#

Well I don't have one being called from the Load method

silent tapir
cosmic rain
#

Well, one of them doesn't have the correct reference at the correct timing, so all you need to do is just figure out which one has the wrong reference and where it is assigned.

silent tapir
#

alr

silent tapir
vague tinsel
#

velocityY is not 0 , its showing very abnormal value

#

also i am randomly flying in air, any idea what might be happening

static pollen
#

can anyone help me here?

crisp minnow
#

velocityY is not 0 , its showing very

proven jasper
#

Going a bit nuts on this because I'm clearly missing something very obvious. Null ref on the foreach (not within it), but the collection is not null (and reports the correct count in the prior debug) ``` public EntityInstanceManager(Func<List<EntityInstance>> getInstancesFunc, Func<NativeEntityInstance> getNativeFunc, Ship ship)
{
GetInstancesFunc = getInstancesFunc;
GetNativeFunc = getNativeFunc;
Ship = ship;

        var entities = getInstancesFunc() ?? new List<EntityInstance>();
        Debug.Log(entities.Count); // correctly reports positive number
        foreach (var entity in entities) // throws NullReferenceException
            entity.Manager = this;
    }```

EDIT: Fixed. IDE linecount was off for whatever reason, go figure.

simple egret
soft shard
# proven jasper Going a bit nuts on this because I'm clearly missing something very obvious. Nul...

Im not sure when, but at some point for some reason, for-loops specifically always report incorrect errors, ive had errors that suggest a line thats literally the } bracket of a for-loop, as if Unitys internal debugger just cant figure out what line of a for-loop is relevant so just marks the whole for-loop as "problem is here somewhere... I think" - good to hear you got it sorted but at least you know if it get another error specific to a for-loop, it might be a misleading debug from Unity itself (at least, AFAIK)

simple egret
#

I got a few like these but with IndexOutOfRangeException, they would always report at the end of the block even if the array indexing (that was faulty) was 10 lines above that

#

And it is the compiler Unity uses, since it doesn't happen in regular .NET apps

knotty sun
queen saffron
#

thanks!

upbeat arch
#

How to make custom sliders

knotty sun
upbeat arch
#

Idk how to create a custom slider

knotty sun
#

google

upbeat arch
#

German ?

leaden ice
hollow pine
#

Hiii, really new here is there any code the limits the rotation degrees to a certain point, ex this object can only rotate 90°. Thank you

fleet gorge
#

so how would you like the rotation of your object to be limited? do you have any visualisation for it?

hollow pine
upbeat arch
leaden ice
ruby nacelle
#

Hey it's my first time mapping a controller input for a game, should you use a virtual mouse to control the look action or should you use Cursor warping?

leaden ice
ruby nacelle
#

Interesting, Unity automatically shoves them into the same action so I assumed you could just map it to the same thing

#

I quite honestly don't know much about remapping inputs or using anything other than Keyboard and mouse so I was wondering if anyone had resources on the matter

leaden ice
#

Wdym by remapping

#

That sounds like a different question

ruby nacelle
#

Sorry what I mean is that I am looking to set up a controller for my game and I am wondering how to map the right stick to the mouse cursor

leaden ice
#

I just explained this is usually a bad idea

#

And not the right way to handle things

ruby nacelle
#

So how should I go about it

ruby nacelle
#

Yes, I created a new action that is exclusively mapped to the controller

#

But I want it to be able to control the cursor

leaden ice
#

First you said it was for a Look action though

#

What's the intended goal here

#

Do you actually want it to control a cursor, or just to make the character look around?

ruby nacelle
#

Sorry I think there's a lack of clarity on what I am trying to do, in the game the the player has to use the mouse cursor to fire and pickup objects but I also want to offer the opportunity to use a controller if the player wants, I am trying to map the right stick to that same type of function

#

and I'm not sure how to go about it

fading umbra
#

Hey, what is the best way to make FPS animation in Unity (Arms or full body animation) and the best way to learn it? Any tutorials?

timid brook
#

any1 know how to do faux movement on rotating spheres? I've been struggling for a long time trying to make the movement work both with physics and without, this current example is fully with physics

hybrid wagon
fading umbra
hybrid wagon
hybrid wagon
fading umbra
#

No problem just learning

timid brook
#

when trying to move forwards for example, it moves weirdly, i can send you a video

fading umbra
#

Yea sure I will be happy

#

If I get any problem in the future can I personally ask u guys?

fierce tundra
#

basically when running the game, the sound sounds quite normal, but when building it, its messed up

hybrid wagon
#

please make sure OBS is recording mp4 not mkv , so we can see the video

fierce tundra
#

alr

#

one secon d

#

basically when running the game, the sound sounds quite normal, but when building it, its messed up

timid brook
#

during the entirety of this video i was holding W (PS: this works fine when the planet isn't spinning)

hollow pine
timid brook
#

it's really annoying and I have no idea how to fix it

hybrid wagon
# fierce tundra

can you please just download any mp3 file from internet and make a new gameoject and add to it audio source and test again

hybrid wagon
timid brook
timid brook
hybrid wagon
hollow pine
wide terrace
# hollow pine Hi guys, just wondering, if you guys got any idea about this, the bullet is kind...

Looks to me like it's shooting accurately, but not taking into account the height of the guns. That is, your mouse hits a point at ground level and the player rotates to face that point at ground level, but the projectiles travel on a higher plane parallel to the ground plane.

Maybe this script could acquire the height of the guns from _player and just set the plane to that height?

(I might be misinterpreting the issue)

fierce tundra
hybrid wagon
timid brook
#

but orientation is literaly the camera's forward:

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

public class MouseLook : MonoBehaviour
{
    [SerializeField] private Transform _orientation;
    [SerializeField] float _sensitivity;
    float _xRotation;
    float _yRotation;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        _yRotation = -180;
    }

    void Update()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * _sensitivity;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * _sensitivity;

        _yRotation += mouseX;
        _xRotation += -mouseY;

        _xRotation = Mathf.Clamp(_xRotation, -90, 90);

        transform.localRotation = Quaternion.Euler(_xRotation, _yRotation, 0);
        _orientation.localRotation = Quaternion.Euler(0, _yRotation, 0);
    }
}

hybrid wagon
hollow pine
hybrid wagon
#

just drag it outside every parent , let it stand alone

hybrid wagon
timid brook
#

no, it's a separate game object, that keeps track of only the y rotation of the camera

#

it's parented to the player

hollow pine
glossy vessel
#

Hello, I'm trying to find an asset (might even be in FEEL already) to debug values into gui for easy debugging

#

Some sort of queue system for debugging that displays GUI

strong badger
#

does anyone have the link to the offical unity server

somber nacelle
strong badger
#

ok

hybrid wagon
hollow pine
#

when i move it out

hybrid wagon
#

because unity work with parent-child system , so parent apply its rotation to child

wide terrace
# hollow pine possibly, and it kinda aims also correctly when it's in up and down position

That's what makes me think that the vertical offset is an issue... Like, if you draw a line upwards from your cursor to the height of the projectiles, I reckon that point of intersection is where it appears to be effectively aiming, rather than directly at your cursor.

For a quick test, you could swap out the Vector3.zero in plane = new Plane(Vector3.up, Vector3.zero); with a vector that has a y component roughly reflective of the guns' height.

If the projectiles not crossing at the cursor is also an issue, I think that's a separate problem to be addressed and what Hussien is getting at 👀

hollow pine
hybrid wagon
#

@hollow pine wait let me understand , is your issue that the bullets are going out as X shape right?

#

you want them to move in straight line

wide terrace
#

Yeah I guess I should have asked for more clarification as well, instead of assuming 😅

hybrid wagon
hollow pine
#

sorry for wording this all poorly haha

hybrid wagon
#

so you can debug it easier

hollow pine
hollow pine
wide terrace
#

So, assuming the player object already has access to that data, I would have CubeScript store a reference to the player script, and retrieve that height from there. That way if you swap out player models or weapons or something down the road, the script would continue to use the correct vertical offset

worn crystal
#

Ive got a custom script Im using to set the parent size to the largest child height, but for some reason it only updates once I tick the fit to height box a few times, Im making sure to set the whole thing as dirty but still no luck

#

the height updates properly but the layout group wont properly reposition the element

#

heres the code

hollow pine
#

Ok, will try it out, @vague basalt and @hybrid wagon Thanks guys

hybrid wagon
worn crystal
#

pretty much

#

but with unitys build in stuff it seems i cant get it to work right

#

heres an example with trying what unity recommended:

hybrid wagon
#

are you using vertical layout group?

worn crystal
#

yeah

somber tapir
#

what's the height on the text components?

worn crystal
#

the height is correct on the text components

#

but the position is wrong

#

or actually wait, the height is wrong on the parent of the text component

#

which is weird since i have the layout group/contet size fitter

#

oops nvm, was looking at the wrong field, height is correct

somber tapir
#

what happens if you change it to:
Child Alignment: Top Left
Control Child Size: Check Height
Child Force Expand: Remove Height

#

and you also need to add some Top Padding

worn crystal
#

control child size being ticked off might be it

#

padding is optional def

somber tapir
#

It's definitely possible with the Unity UI System, I recommend playing around with that rather than trying to come up with your own solution.

worn crystal
#

also this is an in game issue only, in editor it works fine

#

presumably because it looks like in editor specifically they have code that runs that manually marks the layout to rebuild every frame

topaz galleon
#

any tips here?

knotty sun
topaz galleon
worn crystal
#

needs to be assigned something

topaz galleon
#

if i do this?

worn crystal
#

that works

knotty sun
topaz galleon
#

so what actualy is the difference between

float currentAng = 0f;

and

float currentAng = 0;
worn crystal
#

one is a float and the other isnt

topaz galleon
worn crystal
#

might attempt to cast the number from an int or double to a float? microoptimization but also just best practice to append f to float numbers when assigning them

worn crystal
#

i dont know 100% if itll do that

#

or if the compiler will catch it

knotty sun
#

also

flaot a = 0.1f

is correct

float a = 0.1;

is an error because 0.1 is a double
it is ALWAYS good proctice to use the f suffix when dealing with constant float values

topaz galleon
#

yea, when i use decimals then i use the f but if not then i dont

worn crystal
#

its just a best practice thing

#

for using it on 0

spring creek
spring creek
#

The f is the exact same as writing
float thing = (float) 0

It is just shorter.
Syntactic sugar

topaz galleon
#

aah

topaz galleon
wintry jackal
#

Hi there!

My problem is related with class inheritance.
I have many enemies, each with it's own attack Script (EnemyAttackGun, EnemyAttackShotgun...etc), and they all inherit from the class EnemyAttack

When the enemies die I want to disable their attack scripts so they stop attacking while the animation is played.
But since all enemies share the same EnemyHealth script i'd like to avoid having to go through a list of "ifs" to check if the enemy has one script or another (if(GetComponent<EnemyAttackGun); else if (GetComponent<EnemyAttackShotgun)... etc).

Can I use in any way the parent script to avoid this? (something like GetComponent<EnemyAttack>().enabled=false; which I already tested and doesn't work)

knotty sun
worn crystal
#

if theyre inheriting from the same class then callingn getcomponent on the base should def work

wintry jackal
#

give me a null reference

#

i'm gonna try it again in case i did anything wrong

knotty sun
#

then you were probably doing the GetComponent on the wrong gameobject

wintry jackal
#

It gives null reference
Both Scripts are on the same GameObject

The object has this class as a component (public class EnemyAttackGun : EnemyAttack)
The code line i'm using is this one (GetComponent<EnemyAttack>().enabled = false;)

knotty sun
#

screenshot the inspector

wintry jackal
#

the EnemyHealth script is the one trying to disable the EnemyAttack script

toxic harness
#

my door opens like this, please help

knotty sun
# wintry jackal

OK add a Debug.Log before the GetComponent and make sure to include the second parameter to make absolutely sure this is the correct game object

swift falcon
wintry jackal
knotty sun
wintry jackal
#

referencing the class EnemyAttackGun : EnemyAttack as an EnemyAttack : Monobehaviour doesn't work.
I mean, Unity doesn't let you use it

knotty sun
#

what, yes it does, it is common practice.
post both scripts to a paste site

wintry jackal
wintry jackal
knotty sun
#

!code

tawny elkBOT
knotty sun
#

also post the EnemyHealth script @wintry jackal

wintry jackal
#

ok this is weird, after pasting the EnemyHealth code, the lines im tryng to use rn are missing xd

#

Like a previous version of the code. Is that normal? O,o

#

Ok nevermind I was reading smthing else. The lines we want to look at in EnemyHealth are 119-154

#

void Die()

knotty sun
#

I think you may have compile errors, is your IDE configured?

wintry jackal
#

131 is the line giving null reference

knotty sun
#

that is a run time error

wintry jackal
#

and no errors displayed on the console.

tawny elkBOT
wintry jackal
#

I'm using VS 2017

#

should that be a problem?

spring creek
wintry jackal
#

also atocompletion and underlining errors etc is working fine

spring creek
#

Just gotta do the steps outlined in the guide you were linked to

spring creek
wintry jackal
#

no

#

could it be i've done something wrong with the class inheritance?

#

I think this is allright btw

somber nacelle
#

if you're receiving runtime errors that means you can enter play mode which means you shouldn't have compile errors because unity will prevent you from entering play mode with compile errors

wintry jackal
#

Ok guys

#

Im dumb

#

you can stop investigating

dawn nebula
#

So I'm looking to position points in a sphere formation. I want these points to be equally distributed across the sphere, and I'd like control over how many points there are.
Any tips? For example, a simple UV sphere isn't good because so many of its vertices are concentrated at the poles.

wintry jackal
#

I'm kind of ashamed but, EnemyAttackGun had not been saved yet

#

it works

#

sry for making u lose time :__D

fading jewel
#

hey, does anyone have experience with object pooling?

fading jewel
knotty sun
somber nacelle
wintry jackal
fading jewel
#

anyway, i have a basic pool of GameObjects set up with a max pool size of 30, but when i'm calling pool.Get it's going well over the maximum size

#

and never calling my return to pool method

somber nacelle
#

show relevant code

#

!ask 👇

tawny elkBOT
knotty sun
fading jewel
# somber nacelle show relevant code

i guess the real question is whether pool.Get is what i should be using here or if there's another built-in method for creating/drawing from the pool

somber nacelle
#

are you using unity's ObjectPool class, your own, some other one from some package/asset? We have no way of knowing and you've not shown code

fading jewel
#

unity's ObjectPool class

somber nacelle
#

but typically yes, Get is what you would use to get an object from the pool

somber nacelle
toxic harness
rigid island
toxic harness
#

anyone have a solution

fading jewel
#

if i have a maximum pool size set and the pool goes over, it should be calling the method i set for the release action, right?

knotty sun
toxic harness
rigid island
knotty sun
#

so show the inspector of the door

toxic harness
rigid island
#

you're rotating on the Z which is very wrong

#

and X

#

you should only rotate Y on a door

knotty sun
#

so you have uneven scaling which will cause problems when rotating

rigid island
#

that too

toxic harness
#

how can i fix it

rigid island
#

make the child door(the one with the graphics) position, match the parent on the Hinge part of the door (the corner where doors normally rotate from)
after that rotate the parent object on the Y position

toxic harness
#

the door doesnt work now, i dont even get the 'click e to open' oiption

fading jewel
rigid island
#

start with fixing the rotation and movement first

toxic harness
#

rotates on hinge

rigid island
#

rotation

toxic harness
rigid island
tawny elkBOT
toxic harness
fading jewel
#

ah, ok. so the max pool size isn't a cap on how many objects can be in a pool

rigid island
somber nacelle
toxic harness
#

same thing

#

should i have the door script on the parent or child

#

its on the child rn

rigid island
toxic harness
#

wdym graphics

rigid island
#

collider too

fading jewel
rigid island
toxic harness
#

oke

fading jewel
#

seems like calling pool.Get() is creating new active objects rather than inactive

toxic harness
#

now ive lost the open door function, im clicking e

fading jewel
#

do i need to populate my pool with inactive objects at start?

rigid island
#

where is the script that supposed to open door with E

toxic harness
#

i sent the script

#

ohhh

rigid island
#

thats the door script

toxic harness
#

sending inab

somber nacelle
toxic harness
rigid island
toxic harness
rigid island
#

this collider doesnt seem to have the proper sizes / offset

fading jewel
somber nacelle
#

you just Release them to the pool

fading jewel
#

ahh ok, got it

#

thanks for the help!

toxic harness
rigid island
rigid island
#

oh you're using UseLayers in code

#

yours is on Default

#

thats probably not the uselayers is it

#

Ah yes I see here its the Usable layer

#

change it and should work

fading jewel
toxic harness
#

OI NAVARONE

#

U R SUM GENIUS

#

THANK YOU BRU

#

is there a way to add a creaking sound during the animation tho

rigid island
toxic harness
#

hmm new issue now

#

i cant brign the text closer to the camera

#

so its blocked off

#

top is game view

rigid island
misty blade
#

alright, thanks

rigid island
toxic harness
#

its a text..

#

im not sure tbh how this all works

rigid island
#

Why is the text a world canvas if you dont know what that is..

toxic harness
#

ytber again

#

i really should learn this stuff but id like to get a basline done soon

#

how can i move the canvas

rigid island
#

if you dont learn you cannot progress..

#

just copying tutorial doesnt teach you anything, its mainly to show you how to do something, its up to you to learn this stuff on your own

#

otherwise you're copy and paste, and that has no effect on experience

#

https://www.google.com/search?q=world+canvas+vs+canvas+unity

Unlike a Canvas set to Screen Space, a World Space Canvas can be freely positioned and rotated in the Scene. You can put a Canvas on any wall, floor, ceiling, or slanted surface (or hanging freely in the air of course). Just use the normal Translate and Rotate tools in the toolbar.

toxic harness
#

how can i change

rigid island
#

learn how both work, put a little bit of effort

#

if its a world canvas you need to move it in the world like any other gameobject and it gets hidden by walls, if you use Overlay you will have text on screen then its up to you using WorldToScreen to place it on specific objects

#

both are mostly design choices with their own pros and cons

#

figure it out which one works best

dawn nebula
#

Hey so in this image, on the left I have a Cube Mesh while on the right I have a VFX graph system that spawns a single cube particle.

#

The particle appears to be smaller than the mesh, even though the particle has a scale of 1.

#

What determines the scale of these particles relative to the rest of the world?

leaden ice
hexed oak
#

Is there a way set occlusion cull to everything when a canvas is overlaying the whole screen?

leaden ice
#

Maybe just render the UI on a different camera and disable the other one when it's visible?

turbid seal
#

I want to move a 2d gameobject in a perfect circle, how to do it? Without using parent/child (with script)

#

Tag me please

steep herald
#

@turbid seal cos(angle) for the x, sin(angle) for the y, angle is in radians, 0 aims at worldspace right, TAU is full revolution counter clockwise

turbid seal
turbid seal
steep herald
#

@turbid seal No 🙂 If I did, it wouldn't be as much fun

You have the wonderful unity mathematics library at your disposition. The process is simple, for any given angle, cos and sin will return your x and y values for a circle of unit length. If you want a bigger/smaller circle, multiply those values by the desired radius.

Interpolating the angle works the same as interpolating the value of anything else. If you've ever moved something outside of the physics simulation, this is no different.

Remember cos and sin, along with trig functions in general, work with radians, not degrees. If you prefer to work in degrees, you need to convert it to radians before passing it into trig functions.

https://docs.unity3d.com/ScriptReference/Mathf.Sin.html
https://docs.unity3d.com/ScriptReference/Mathf.Cos.html
https://docs.unity3d.com/ScriptReference/Mathf.Deg2Rad.html

turbid seal
steep herald
#

Let's be real, I do it for myself. But no prob

turbid seal
steep herald
#

Sharing is fun

turbid seal
rancid gulch
#

Hey guys, so I'm using IPointer handlers for some basic functions in unity. When I run it in the editor its all good and works just fine, but I build an apk for android and suddenly it does not work on mobile, can anyone help me?

chrome trail
#

I have two projectiles set up so that the only intersect with each other for a single frame and want it so that at least one can see the other for that single frame. One has no collider with this script attached

{
    //For the sake of this specific variation of the script, the speed is exactly 60 because that's what is required for the two objects to intersect for a single frame 
    const float SPEED = 60;

    //Misc variables
    Vector3 trajectory = Vector3.forward;

    // Update is called once per frame
    void LateUpdate()
    {
        //The idea is that, after everything else in the scene has moved, the projectile checks its immediate area and trajectory for anything it can hit
        //If it does, I should get a message telling me something was hit
        //Otherwise it moves to the next spot along its trajectory

        bool immediateArea = Physics.CheckBox(transform.position, Vector3.one * 0.5f, transform.rotation);
        bool movePath = Physics.BoxCast(transform.position, Vector3.one * 0.5f, trajectory, transform.rotation, SPEED * Time.deltaTime);
        if (!immediateArea && !movePath) { transform.position += trajectory * SPEED * Time.deltaTime; }
        else { print("Collision detected"); Destroy(gameObject); }
    }
}```

While the other has not just a collider, but a rigidbody attached and is traveling perpendicular to this projectile at the same rate meaning they're meant to theoretically overlap perfectly at a single point on a single frame. However during and after that frame there is no recognition from the above script that an object with not just a collider but a rigidbody ever crossed its path. I thought this might be an issue with ordering so I tried having this script run in LateUpdate but there's still no recognition that it ever hit anything. Why is this?
ionic adder
plush bobcat
weak venture
#

is anyone really familiar with platform effector 2d one way mode? Im trying to fine tune this to be more precise. Basically what I'm facing is there is a sweet spot the player can hit where its triggering my grounded check on the relevant collider but is not triggering the effector one way activation

hollow pine
#

Hi @vague basalt & @hybrid wagon , I fixed it, yeah the height is the problem since it's not being considered
my problem now is how to not get the guns, go through or pass through the body

gloomy helm
#

how do i make the "* new Vector3(0, 0, distFromRightPivot);"

local to rightpPivots[0].transform

    rightPivots[0].transform.localPosition = rightPivots[1].transform.localPosition + Quaternion.Euler(remap(.37f, .5f, 0, 40f, -rightIkTarget.transform.localPosition.z, true), 0, 0) * new Vector3(0, 0, distFromRightPivot);
upper pilot
#

Hey, any ideas on how to scroll a scrollRect to the bottom?
So far anything I tried doesn't work, even forcing update canvas.

        scrollRect.verticalNormalizedPosition = 0;
    IEnumerator ForceScrollDown()
    {
        // Wait for end of frame AND force update all canvases before setting to bottom.
        yield return new WaitForEndOfFrame();
        Canvas.ForceUpdateCanvases();
        scrollRect.verticalNormalizedPosition = 0f;
        Canvas.ForceUpdateCanvases();
    }
slim trellis
#

hey all, i just updated my project from 2020.3.x to 2022.3.42 (latest LTS) and i'm seeing something strange on my android build. i'm curious if anyone else experienced this. basically:

  • Any audio played on AudioSource without loop checked doesn't play
  • Any audio played on AudioSource with loop checked does play
    to test this specifically:
source.loop = true;
source.Play();
source.loop = false;

when i added loop = true just before hitting play, it works (i just have to turn it off right after so it doesn't actually loop). is this expected behaviour in 2022.3.x? there's no issue with audio in editor - this is happening with android builds on device

inner charm
#

I'm doing a sidescrolling game where you also can move up and down (representing fake 3d depth), classic 2D adventure.

Is there any builtin for 2D that helps with the Sprite Renderer's "Order in Layer"?
Right now I'm manually sorting the different sprites so the Box Colliders with the lowest Y gets in front of the ones higher up on the screen. But I'm not the first to make this kind of game, so I'm thinking that maybe Unity has something smart built in?

stable osprey
#

are you saying though that 2020.3 didn't have this issue and 2022.3 does?

stable osprey
#

term you might be looking for is isometric top-down for your camera setup

inner charm
stable osprey
#

np!

inner charm
stable osprey
#

was unsure whether the correct axis is (0, 1, 0) or (0, -1, 0) but nice 😄

stable osprey
inner charm
#

In my mind isometric isn't exactly the same thing, but I might be wrong

#

When I think isometric i think kinda tile-based stuff, but yes, it's probably the same thing, just my perception of it being something else

slim trellis
slim trellis
stable osprey
rancid gulch
timid briar
#

I need to create a script where the player has money and can buy guns off walls

leaden ice
#

Involving many pieces

#

Also don't crosspost

rancid gulch
lean sail
inner charm
#

Because when you can build that, the rest should be easy

mellow rivet
#

Hi! How you guys document/comment your code flow. Imagine you do a Save system, you guys just comment in the code, or use an app like obsidian and explains like "Ey this Manager wil call this so this can be used and this will happen if this is being..."?

lean sail
# mellow rivet Hi! How you guys document/comment your code flow. Imagine you do a Save system, ...

for your own project, or some package that'll be used by others?
For your own project, its not really needed and you'll probably be writing it somewhere when designing the game.
For the latter, i typically see people do stuff similar to the unity docs, or just a straight up PDF in the package. Even unity's ngo has their own docs for it https://docs-multiplayer.unity3d.com/netcode/1.1.0/tutorials/get-started-ngo/

stable osprey
#

and each algorithm that's not self-explanatory should contain enough // comments to make it skim-throughable

#

explaining private fields with summary blocks is overkill imo. A comment at max IF AND ONLY IF the name isn't self-explanatory, or ambiguous with another variable.

lean sail
#

if we're talking about like the flow of the game, which is what i assume from their example, its kinda hard to just put that above a method. It wouldnt always make sense to say "a manager will call this function" and you wouldnt exactly comment it in the managers code cause you would see it called. Otherwise you start to end up with
int a = 1 + 2; // a is equal to 1 + 2

#

although the question also makes me think this is for other people, so id really suggest just making a unity style doc or a pdf

stable osprey
#

public fields/properties you might or might not wanna document based on your plans for the game. Is it a long-term project that you intend to review after years?
If so try to solve the issue via architecture first (e.g.: stop needing this as public), and if everything fails, commenting wouldn't hurt too much.

#

The issue with commenting public fields/properties is that it'd be inconsistent if you only commented very few of them, so you might have to comment everything afterwards

mellow rivet
lean sail
stable osprey
#

I kind of do that and I don't really mind if it's stuff I'll instantly recognize if I see this after say 5 years

#

e.g.: I'll always know what temperature is, but singleLine and preventRefusals can be easy to forget, so I'd rather just look at the comment and know instead of having to go through the code flow

lean sail
stable osprey
#

Yeah I like my code dense lol.. I hate scrolling after a wrist thing I obtained

simple mulch
#

anybody here knows how i can access snap settings?

lean sail
mellow rivet
#

Okeys, thanks @lean sail @stable osprey

static pollen
#

can anyone help me here?

knotty sun
stable osprey
#

why would you forget to update the comments lol

knotty sun
#

haste

stable osprey
#

but yeah important point

#

if you approach that way you need to commit to it

knotty sun
static pollen
stable osprey
#

would probably work best with a dedicated architect in team though -- which is kinda rare from what I see lol

static pollen
stable osprey
#

well, you can fix your issue by making sure the isGrounded bool is true when it has to be.

#

So I'd say keep an eye on that bool and make changes until you get it right 😛

#

that said, each of the parameters there are to be checked and tuned. Starting with the groundMask -- is the sloped platform part of the Ground layer?

simple mulch
#

i set this thing to global but it wont let me open the grid snapping

static pollen
simple mulch
stable osprey
slate pulsar
#

Hello, I am trying to make a voxel system similar to Minecraft and I am working on the textures for the blocks. This is my code that generate a texture atlas:

public void CreateAtlas()
{
    uvRects = textureAtlas.PackTextures(Textures.ToArray(), 1, 2048); // uvRects is a Rect[]
}

And I am getting the rect from a Rect[] using this method:

public Rect GetTextureRect(string name)
{
    var index = Textures.FindIndex(0,x => x.name == name);
    if (index >= uvRects.Length || index < 0)
        return default;
    return uvRects[index];
}

This method applies the UV to the blocks:

private void AddTexture(string textureID)
{
    var uvRect = BlockSystem.Instance.GetTextureRect(textureID);
    uvs.Add(new Vector2(uvRect.xMin, uvRect.yMin));
    uvs.Add(new Vector2(uvRect.xMax, uvRect.yMin));
    uvs.Add(new Vector2(uvRect.xMax, uvRect.yMax));
    uvs.Add(new Vector2(uvRect.xMin, uvRect.yMax));
}

It does apply the texture on each block, but it seems to be sideways and stretched (shown in the attached image).

stable osprey
static pollen
stable osprey
#

moving groundCheck object up or down a little should fix it

static pollen
#

if I increase the Ground Distance it will work, but yea as I said the palyer will fly

stable osprey
#

just make sure it won't break too much

stable osprey
#

I'd start with the groundCheck object

knotty sun
static pollen
knotty sun
#

the collider on that floor tile because I dont see the gizmo in your screenshot

static pollen
#

it has a boxcollider

knotty sun
#

I know it's a box collider, I can see that in the Inspector, but I dont see it on the scene view

knotty sun
# static pollen

ok, that good, so If you want to Raycast from the player to that floor tile your cast direction should be -floorTile.transform.up so you are raycasting down taking into account the slope of the floor tile

#

then your ground distance is no different than if you were walking on a flat tile

inner charm
#

Is there a smooth way to retrieve a field from a list, where another field is x?

Pseudocode for what I want:
myhp = List.Find(Character = gameObject, characterHP);

I'm doing this with for-loops at the moment, iterating through the entire list. And I have a feeling that there is probably a better way which I have yet to grasp 🙂

knotty sun
thin hollow
#

Is there a way to move rigidbody to a new position with triggering collisions along the way? I'm making a hitbox collider that should deal damage to the enemy on OnTriggerEnter(), but if the animation of the movement is too fast - it phases right through the enemy and doesn't do anything.

         void LateUpdate()
        {
            //_hitboxParent is the bone Transform which the hitbox is supposed to follow in the current attack
            if (_hitboxParent && data)
            {
                // tried this
             // transform.position = _hitboxParent.position;
                // and this...
             // transform.position = Vector3.Lerp(transform.position,_hitboxParent.position,0.75f);
                // this doesn't work either...
                GetComponent<Rigidbody>().MovePosition(_hitboxParent.position);
                transform.rotation = Quaternion.identity;
                
                if (!_hitbox.enabled && timeSinceAttackStart > data.attackDelay)
                    EnableHitbox();
                
                if (_hitbox.enabled && timeSinceAttackStart > data.attackDelay + data.attackDuration)
                   DisableHitbox();

            }
            else
            {
                transform.localPosition = Vector3.zero;
                if(_hitbox.enabled) 
                   DisableHitbox();
            }
            if (debug)
                DebugEx.DebugLocalCube(transform,_hitbox.size,_hitbox.enabled?Color.green:Color.grey,Vector3.zero,Time.deltaTime);
        }
inner charm
inner charm
# knotty sun what type is characterHp ?

It's int, so I understand that somehow it could work, I just can't comprehend how. Or well, I could put it "outside" of the CharacterInstance object, but I feel that it'll get more complicated?

#

This is the CharacterInstance:

{
    public CharacterData characterType;
    public bool inUse;
    public string owner;
    public int hp;
    public InputController inputController;
    public GameObject instantiated;

    public CharacterInstance(CharacterData characterData, GameObject instanceOfCharacter)
    {
        characterType = characterData;
        hp = characterData.basehp;
        inUse = false;
        owner = null;
        inputController = null;
        instantiated = instanceOfCharacter;
    }
}```
#

(It maps a character to a player, and it also holds hp of character, and maybe more stuff in the future)

knotty sun
inner charm
#

I don't fully understand this yet, but I feel that it'll soon click 🙂

knotty sun
inner charm
thick terrace
#

it might be faster to use a dictionary if you have lots of entries, but this is simpler and uses less memory, so as always you'd want to use the profiler to decide if performance is an issue

lean sail
inner charm
thin hollow
# lean sail <https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html> Are you loo...

What you're describing (and the code) doesnt really make much sense. Animation doesn't use rigidbody movement.

Hitbox is a separate script that follows a set transform. In this case it's a bone of a character. What doesn't make sense here? How would you do it?
I tried to use SweepTest, but now I have a super weird issue that SweepTest result colliders don't have attachedRigidBody defined for some reason, so I get null reference exception errors in OnTriggerEnter():


                Vector3 oldPos = transform.position;
                transform.position = _hitboxParent.position;
                var hits = GetComponent<Rigidbody>().SweepTestAll(transform.position-oldPos,(transform.position-oldPos).magnitude,QueryTriggerInteraction.Ignore);
                if(hits.Length >0)
                    foreach (RaycastHit hit in hits)
                    {
                        if(hit.collider != null)
                        {
                            OnTriggerEnter(hit.collider);
                        }
                    }


        private void OnTriggerEnter(Collider collision)
        {
            // stop hitting yourself! This if is generating null error
            if (collision.attachedRigidbody.transform == _owner.transform || 
                collision.attachedRigidbody.transform == _hitboxParent.transform) return;

            TryDoDamage(collision);
        }
knotty sun
#

Only one side of a Trigger or Collision has to have a Rigidbody, so if this object has one then the chances are what it hits does not

thin hollow
knotty sun
ionic adder
# rancid gulch No errors, they aren't even being called I checked it out with logs

The script implementing the handler interface is on a UI element, yes? It needs to be.

Are you getting any other types of touch input in your build? Try logging Input.touchCount. Add a default UI Button - does it register taps? Do you have an EventSystem in your Scene? Is Block Raycasts enabled on the UI with the handler Script on it? Is there a Graphics Raycaster component on the GameObject with your Canvas? Is there another UI element in front of it preventing Raycasts from hitting it?

sharp juniper
#

So I'm making an online board game and I want to code a check to highlight a circle in the gameboard grid. I have a point for each grid and it has a highlight object. How can I do this check?

#

something like this

#

and it highlights the nodes in that area

fringe ridge
#

What do you mean by highlight, im having trouble understanding what you want to do

sharp juniper
#

activate an object in each node

knotty sun
# sharp juniper something like this

Simple math
you have a central point of the circle
You have the radius of the circle
So you have the area covered by the circle
Each node should change if it falls within this area

sharp juniper
#

that's the higlight I want

static pollen
sharp juniper
knotty sun
dusk apex
sharp juniper
#

yeah I have an integer for both

sharp juniper
stable osprey
#

I don't have OCD but watching this image for too long might give it to me lol

stable osprey
# sharp juniper something like this

That's simpler than it sounds:

var hitObjects = FindObjectsOfType<Highlighter>().Where(x => Vector2.Distance(x.transform.position, mouseWorldPosition) <= radius);
foreach (var highlight in hitObjects) { highlight.Highlight(); }

You could also go with physics if you got colliders:

var hitObjects = Physics.OverlapSphere(....);
foreach (var obj in hitObjects) { obj.GetComponent<Highlighter>().Highlight(); }
#

but your objects are very weirdly positioned. As in they don't appear to be on the center of their grid cell.

sharp juniper
#

The circle doesn't seem good. I had to change the code to be d <= radius to get this result in the first place but I don't know what I'm missing``` var radius = DistanceMultiplier;

            for (int i = 0; i < SpawnedMap.Columns.Length; i++)
            {
                for (int i2 = 0; i2 < SpawnedMap.Columns[i2].transform.childCount; i2++)
                {
                    var d = Mathf.Sqrt(((Col - i) * (Col - i)) + ((Row - i2) * (Row - i2)));
                    if (d <= radius)
                    {
                        SpawnedMap.Columns[i].transform.GetChild(i2).GetChild(0).gameObject.SetActive(true);
                    }
                }
            }```
knotty sun
wintry gust
#

Does destroying a UI Button automatically clean up any Listeners it has added to it, or is that something I have to manage myself on destruction?

sharp juniper
knotty sun
#

no, a circle

sharp juniper
#

ok

elfin ridge
#

my code doesn't compile nor it reloads domain after i close the code, my script has no errors nor warns.

#

i tried reopening unity

#

but didn't work

wintry gust
elfin ridge
knotty sun
sharp juniper
wintry gust
knotty sun
sharp juniper
#

ok

inner charm
#

I have a feeling that this is an ugly way of getting a reference/pointer/whatisitcalled to the weapon I'm about to swing:
WeaponObject = this.transform.Find("weapon");
While it works well, and I'm not sure that it is ugly, I kind of don't like the free text search for my weapon like this. Anyone who can point me in the direction of best practice?

sharp juniper
#

First is when its 1, second is second, third is third. I can't really show it properly as its using the columns for making the circle and not the actual distance of scene

cosmic rain
inner charm
sharp juniper
#

I think I might have found the issue

#

didn't fix

#

the circle is still broken

stable osprey
elfin ridge
#

!code

tawny elkBOT
stable osprey
#
code here
elfin ridge
#

why does my script have an error in line 16 ? "Vector3" does not contain a constructor that takes 4 arguments.

here is my script:

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

public class Floater : MonoBehaviour
{
    public Rigidbody rigidBody;
    public float depthBeforeSubmerged = 1f;
    public float displacementamount = 3f;

    private void FixedUpdate()
    {
        if (transform.position.y < 0f)
        {
            float displacementMultiplier = Mathf.Clamp01(-transform.position.y / depthBeforeSubmerged) * displacementamount;
            rigidBody.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y), displacementMultiplier, 0f), ForceMode.Acceleration);
        }
    }
}

i am following this tutorial: https://www.youtube.com/watch?v=eL_zHQEju8s

In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.

Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4

⎯⎯⎯⎯⎯⎯

Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/

Discord s...

▶ Play video
stable osprey
#

we don't know what line is line 16

elfin ridge
stable osprey
#

however you pass 4 parameters to the new Vector3() constructor, but it only accepts 3 (one for x, one for y, and one for z)

elfin ridge
#

rigidBody.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y), displacementMultiplier, 0f), ForceMode.Acceleration);

sharp juniper
stable osprey
#

you find the excess parameter and delete it

stable osprey
elfin ridge
stable osprey
#

yeah but take a minute to find out WHY

elfin ridge
#

coz its 0f

#

nil

sharp juniper
#

steve I think I fixed it I remoeved the <= and just added 0.5f to the radius

knotty sun
sharp juniper
#

I'm using the int grid I have to detect the circle

#

this is with a radius of 2 and its way much better

knotty sun
sharp juniper
knotty sun
#

you are clearly highlighting something outside the circle

sharp juniper
#

because the radius for the overlap sphere doesn't match with the grid radius

#

I have the radius set for 2 tiles but for the sphere its just a scale factor of 2

#

so the sphere wasn't catching up

knotty sun
#

I have no idea what you mean by that

sharp juniper
#

so I have an int for the column and an int for the row. I make a circle with those ints and expand with that. But the gizmo is taking the same radius I use for the grid without any other scaling. So its just aimlessly growing in size

stable osprey
# elfin ridge coz its 0f

NO! It's because the other values are the X, Y, and Z you want.. the 0f just doesn't have any meaning there 😛

spring creek
stable osprey
#

as expected from the real vsauce koboldthumbsup

stable osprey
#

keep up the good videos coming man

grizzled vine
#

Trying to code some smarter AI, basically, I wanted to have them locate a point on a Navmesh, where they can see the player to shoot them.

I thought I was being somewhat smart by creating a bunch of nodes (Spacing defined) on a Navmesh, and looping through them every X frame to see if they could shoot the player, however, the problem is I'm doing roughly 2300~ Raycasts (Potentionally more.) Every X frame.

Anyone have any thoughts on a better way to handle this I suppose?

open plover
#

Lets say there is a class A. A contains a string, and I want to be able to access a specific A with the specific string. Should I use a dictionary<string, A> or just have an list<A> and use LINQ to access that specific A? I'm asking in terms of performance

naive swallow
#

You might use a single Linq query to initialize the dictionary, if you already have a list of A that you want to turn into a dictionary, but your individual access should be through that

open plover
#

One more question: There is a dictionary<int, A> with 100 key value pairs. I also want to have a list with some of the A's from the dictionary. Should I just make a list of ints and access the A's through dictionary[int] or could I have a list of A's? I'm guessing list of ints is better performancewise since the classes hold references

knotty sun
thick terrace
# open plover Lets say there is a class A. A contains a string, and I want to be able to acces...

it's not exactly wrong to say dictionaries are generally better, but it depends on other factors too - O(1) only means it'll scale well with lots of elements, but if your list is small then linear search (with LINQ or otherwise) may actually end up faster, see the first answer here https://stackoverflow.com/questions/908050/optimizing-lookups-dictionary-key-lookups-vs-array-index-lookups

leaden ice
#

There was no indication that a search would be getting done here

#

The question is missing context

#

We don't know the access patterns intended

#

As far as I understand you're debating keeping the int key of the dictionary vs a direct reference?

thick terrace
leaden ice
#

What would be the point of keeping the dictionary key? It seems like just a useless indirection here unless there's some other reason to use the int key instead

leaden ice
#

Since the dict key would just lead you to the reference

open plover
leaden ice
open plover
#

Ok so let me rephrase to clear any doubt

leaden ice
leaden ice
open plover
open plover
leaden ice
#

I don't see any reason not to just have a list of the class references in that case unless you wish to be able to remove things from the list based on the int key or something

velvet rock
#

I have a 2d game that needs to have a perspective camera sometimes. For those cases, I transtion to a 3d camera by using a very low FOV perspective camera to mimick 2D. This works but the camera distance required is very high(>8000, FOV = 1). Are there any floating point or some other issues with using a perspective camera with such high distance?

The transform.position.z of the 2Dsprites are unlikely to be more than 40. So basically total camera to object distance is never more than 10,000 on the z axis. I also do screenpointtoraycast but that hasn't been a problem(yet). Is there any other risk at using a perspective camera for a 2D scene at such high camera distance(ex: floating point)?

maiden fractal
velvet rock
#

cinemachine blends don't work between ortho and pers

maiden fractal
#

makes sense ig

velvet rock
#

I'm asking about stability of low FOV high cam distance perspective camera for 2D scenes because I'm thinking about ditching ortho camera for it. I have a lot of issues with 2D sorting with ortho camera. But no sorting issues with pers. I also have to make compatible with both.

dawn nebula
#

What sorting issue are you getting? The two camera types shouldn't really affect that.

velvet rock
maiden fractal
# velvet rock I'm asking about stability of low FOV high cam distance perspective camera for 2...

I don't know enough about the way unity cameras work to be able to answer the precision issue question but if you want an alternative solution, actually there is one other way but it is a bit of hassle to get working. The way it would work is by setting Camera.projectionMatrix to a custom matrix which can be lerped between Matrix4x4.Perspective and Matrix4x4.Ortho. I did that in one of my projects but it's couple years ago so don't remember any specific details. I think I did that by just lerping the individual elements of the matrices to get the final matrix

dawn nebula
dawn nebula
#

If you keep the clipping plane range small it should be alright? I'm not completely versed in this.

velvet rock
#

I noticed that the z diff needs to be pretty high to sort properly

dawn nebula
#

Messing with the camera projection matrix like @maiden fractal mentioned is probably the "correct" way to do this.

#

Like when I think high distance low FOV cameras I think FoVs of 5 and distances of ~100.

#

So 8000 is pretty nutty.

velvet rock
#

The other reason i want to switch to pers cams is sorting layers. I haven't used them in this project but I've heard that sorting layer is prioritized over z distance in ortho camera. This'd be problematic as I'd need to replicate sorting layers for each z axis layer after moving objects.

#

It'd be better to just switch over to pers camera now if that's the case.

dawn nebula
velvet rock
# dawn nebula Are you visualizing sprites or opaque meshes?

Just tilemap layers. Like this:
https://www.youtube.com/watch?v=0Eph3Ci9cyM
Except you can mess up the layers.

The world is ruined; mankind is gone and all that remains are robots. But for Poncho, the adventure is just beginning! Explore an open world full of colourful characters, leaping between parallax layers to overcome obstacles and solve puzzles. Can you make it to the Red Tower, meet your Maker and ultimately save humanity?

Subscribe for more Nin...

▶ Play video
#

Everything is sprites. No meshes

#

Ok I think I messed up a bit on the FOV calc. It's ~800 ish camera distance on the z axis not 8000. Is that still bad?

soft shard
# grizzled vine Trying to code some smarter AI, basically, I wanted to have them locate a point ...

I dont think you should need to loop through every node, just the ones that are around the AI that is intended to have line-of-sight (LOS) with the player, another option if you dont have many AI, is to fire a linecast from your AI in the direction of one of your nodes or from a global player reference, if it hits something that is not the player then there is no LOS, otherwise if you have a lot of AI your node system sounds like a scaled approach that can allow a hivemind-type manager to update your AI

grizzled vine
# soft shard I dont think you should need to loop through every node, just the ones that are ...

There might be some misunderstanding here.

So the idea being is each node updates when the player moves, to inform the AI that they could be in LOS of the player at the node. The AI then moves towards that node to shoot the player.

If the AI was more dumb, it could, in theory, just run towards the player and shoot. However, in tighter corridors/objects blocking/etc, it could end up behind an obstacle shooting or just picking random points until it happens to be in LOS.

In terms of it being a "Hive Mind" these nodes are already updated in a single instance, not per AI. Each AI has access to these nodes and they're not running the checks individually

https://gyazo.com/348ee1d5b27f5c6a6a4f626ed999eb7d.

#

(Yellow indicates they can shoot the player from that position. Green is a higher priority in terms of the position where they should go, Red means they can not.)

#

And the reason for Yellow vs Green at the end of the day, is due to the fact that in some levels, the AI can't directly walk towards the green location, but they can still shoot the player. As such, they should still shoot the player.

mellow rivet
soft shard
# grizzled vine There might be some misunderstanding here. So the idea being is each node updat...

Ah I see, if you already have a Hive Mind-like structure I think your approach seems fine, if you absolutely have to update every node every x frames, a raycast does sound like the go-to approach, otherwise maybe you could try something similar to A* with distances/scores and neighbors, or store the nodes in a collection type that can remove nodes with a score of 0, for example if all your AI and player is generally in the center of your map, its unlikely the nodes at the edge of your map need to be updated as even if the player moves, it wouldnt be a scenario your AI could see a score above 0 for those nodes, it might not help by a large amount but could cut maybe 15% of your node loop

soft shard
muted crane
#

Hi folks, I don't exactly know where to post my question, as it seems both trivial and difficult at once:
I'm having a class implementing the Singleton-pattern. Let's just call it the class "Singleton". It is written as followed:

    public static Singleton Instance { get; private set; }
    
    void Awake() {
      if (Instance != null && Instance != this) {
        Destroy(this);
      } else {
        Instance = this;
      }
    }
  }

I have two Scenes, A and B. Both scenes contain a GameObject with the Singleton-class attached.
Scene A starts first and sets the Instance to it's GameObject. The moment I switch to Scene B, the identical GameObject is also settings it's Instance.
Now as I switch from Scene A to B, the static Instance is "transferred" to Scene B and persists separately from the Instance in B.
This is a huge problem for me, because I expected the Singleton-class in Scene B to auto-detect that Instance has already been set in Scene A (as the Awake()-method intentions). But now I have two entirely different Instances running during Scene B.
Especially cases where the Singleton has a reference to another (non-persisting) GameObject are bad, because the moment I switch scenes, the Singleton throws errors.
Is that a known bug or did I miss something crucial regarding the creation of Singletons in Unity? Is there a proper way to remove an "old" Instance from a previous scene?

#

I tried a cheap shot with destroying the Instance with OnDisable(), but that's too shady to do

simple egret
#

Usually it's the "old instance" that's kept, and the ones that are trying to be created in further scenes, destroyed

#

You do Destroy(this), so you'll still see the object in the hierarchy but it won't have the Singleton script on it.
Use Destroy(gameObject) to destroy the whole object

#

Persistence through scene changes should be made with a call to DontDestroyOnLoad(gameObject) in Awake, right after you assign the static Instance property

#

This transfers the object to a scene that's never unloaded, effectively keeping the whole object until you destroy it, or the game is closed

muted crane
#

Yeah I got that far and that's what I sticked with, I was just curious if there was a way to keep an Instance per Scene, not across all of them. Thanks for your help though.
What I used to work with is a "GlobalAccessor"-class finding all GameObjects by tag and serving as a public connection between scripts, might stick with that again

simple egret
#

This breaks the singleton pattern, it's not a singleton anymore if the static instance changes from time to time!
If you're not planning on transferring data between scene changes, you most likely don't need that persistence
But yes you can still use the pattern without the persistence, as long as all the references to scene objects are "refreshed" on Awake

inner charm
#

My animated sprites works ok in my game, but is there any way to see the animations in the inspector? I have one that doesn't work well, and I wish I could find a way to preview it

#

(I havn't done any skeleton link animation stuff, just regular sprites from a sheet)

simple egret
inner charm
simple egret
#

The same can be done with prefabs, open the prefab and follow the instructions as usual

inner charm
wary ferry
#

anyone here have any thoughts on using vs versus vs code? i've been using vs for forever but I like code for non-unity projects. Is the support good?

somber nacelle
#

visual studio > vs code

wary ferry
#

Everything does seem pretty customizable and works well in vs, at least I don't have to restart it lol

lean sail
#

A lot of languages will have extensions on it, when the language itself doesnt have a good IDE. Like when I used ocaml, the IDE at the time was worse than python IDLE

grizzled vine
#

Hmm, yeah its still slowing down my game a fair bit, however, I narrowed it down to the NavMesh.CalculatePath call in my case. That appears to be causing the slowdown the most.

Each enemy is calling the following every frame. (Can be reduced TBF, hower I am still concerned it'll be a problem?)

NavmeshLineofSightHelper.Instance.HasPossiblePoint(agent, item)

Where that calls:

foreach (var item in tetherPoints[GetHeightModifierAsFloat(inShootHeight)]) {
            if (item.canSeePlayer && CanReachPoint(inAgent, item.point)) {
                return true;
            }
        }

And in this case, CanReachPoint is your standard NavMesh.CalculatePath.

I know in most cases, people just make AI go to player, but, trying to make things a bit more smart I suppose?

#

Seems the main cost was the Obstacle Avoidance Quality setting.

#

100 Agents on Screen, Floats around 60~ FPS (With Valorant open in the background in Editor.)

50 Agents I'm at around 140~
The downside to this: They have no Obstacle Avoidance tho.

empty elm
#

Is there some option that allows the child transform to not inherit certain attributes of the parent transform? I don't want the health bar of the enemy to change scale (flip horizontally) but I want it to follow the position and be destroyed with the parent as usual.

cold parrot
zinc parrot
#

How can I convert a 3d render texture to a texture3d so i can write it out to a file? the async one that keeps cropping up online doesnt work, and given that render textures dont have any GetPixels or any similar methods I am kinda at a loss

cold parrot
zinc parrot
#

but you cant do that with a 3d texture right?

#

cuz readpixels only accepts a rect, which is 2d to read

zinc parrot
#

there is a script that uses that that keeps popping up
it crashes my unity

cold parrot
#

maybe check your texture settings and driver/hardware compatibility

zinc parrot
#

OH HECK I GOT IT

#

sorry, it was a issue with stride

cold parrot
#

crashes usually mean segmentation faults

#

so that checks out

zinc parrot
#

yeah

storm wolf
#

is there some event I can subscribe to when I add a new element to an array in the inspector? I know this is a long shot but

cosmic rain
storm wolf
#

whens that called?

#

ah i see

#

thats good thanks

#

yep works perfectly thanks

clever bridge
#

Hello, I'm trying to segregate my player behaviors, and I'm used to using state machines but with Coroutines and collision triggers it's tough to really organize it the way I want to, are there more efficient methods to organizing conflicting player behaviors better than state machines?

soft shard
# clever bridge Hello, I'm trying to segregate my player behaviors, and I'm used to using state ...

I often make them states as well and have a mono as the "manager" for all of them, though my states are usually serialized classes so I can still set references from the inspector as needed, and pass events and properties around for everything else - another option you could look into might be with using interfaces, or possibly scriptable objects if you want to be able to hook up states on AI/non-players through the inspector or generate states and reuse them at runtime

clever bridge
soft shard
# clever bridge So for example, i have a stealth action platformer where the player hides, attac...

I would think your manager should have conditions to prevent conflicting states from playing at the same time, or you could setup some kind of structure (for example, maybe with a Dictionary) that would only allow certain states to play if they are considered "valid", your game logic would need to know that you cant be in a "stealth state" and a "attak state", but it would need to know what to do if you ARE in a stealth state and try to attack, some games may force you out of stealth in favor of the attack or just play a sound letting you know "thats not allowed, you have to change states manually"

gray mural
#

Is Instantiating an empty GameObject and adding the required Components with the AddComponent method less performant than Instantiating a prefab directly?

cunning burrow
#

Quick question, so I checked and apparently TMP does support little icons in the text, but can I make it use my custom icon provider?
For example: <sprite name="resources.gold"> 5000
and then it calls a function like this one: Texture2D GetIcon(string name)
or something like that?
I already know TMP has links which can trigger custom code, but can sprites be loaded from custom code like this as well?

maiden fractal
cunning burrow
gray mural
maiden fractal
gray mural
young tapir
#

Can I somehow invoke an event outside of the class the event comes from? I need to check a bool but I also need the variables from the event which is a lil annoying

#

I should probably put a bit more.. onCoreSnapped has a parameter called "item" which I need to check before I do anything in the event. private void CoreModule_onCoreSnapped(Item item)

simple egret
young tapir
night harness
#

if i have

public class MyBaseClass

public Instance;

public void Start()
{
 Instance.DoThing()
}
public override class MyDerivedClass

public new Instance

those are two seperare vars right? what gets used in Start for derived class?

simple egret
knotty sun
night harness
knotty sun
night harness
lean sail
#

public override class 🤔

simple egret
#

It's obviously pseudocode people

night harness
knotty sun
young tapir
night harness
#

dont have the full context for this so might be bad response but in general ive never had a usecase where i needed to reference a value staticly where just a singleton for that class wasn't a cleaner option

knotty sun
young tapir
#

That seems pretty fair

eager cliff
#

I think it may be off-topic but I dont know where to ask.
My visual studio code enter key is "bugged". The bug only happens in one file with 1500 line + (I dont know if this is problem). What I mean is that normally enter key will start a new line without jumping your screen. But when I press enter, it goes to next line correctly, but it will jump the screen to a different line. Eg. I press enter in line 359, and after I press enter, the screen jump to line 399. How to fix this problem? it is so annoying. I now using shift + enter instead.

vague slate
#

how can I make an algorithm of going through square grid from center to certain radius incrementally?
something like this

#

basically, need a "roll" of offsets

knotty sun
# vague slate basically, need a "roll" of offsets
    void spiralType(int centerY, int centerX, int maxY, int maxX, int type)
    {
        int y = centerY;
        int x = centerX;
        int da = 1;
        fillSpiral(y, x, type, centerY, centerX);
        while (y < maxY && x < maxX)
        {
            for (int i = 0; i < da; i++) fillSpiral(--y, x, type, centerY, centerX);
            for (int i = 0; i < da; i++) fillSpiral(y, ++x, type, centerY, centerX);
            for (int i = 0; i <= da; i++) fillSpiral(++y, x, type, centerY, centerX);
            for (int i = 0; i <= da; i++) fillSpiral(y, --x, type, centerY, centerX);
            da += 2;
        }
    }
    void fillSpiral(int y, int x, int val, int centerY, int centerX)
    {
        if (y < board.n && x < board.n && y >= 0 && x >= 0)
        {
            // Your Code Here
        }
    }

vague slate
#

sorry, but this is extremely confusing example

knotty sun
vague slate
knotty sun
#

board.n is the width and height of the grid

vague slate
#

so say, I just want offsets (meaning start is always 0,0)

#
        void SpiralType(int maxY, int maxX)
        {
            int y = 0;
            int x = 0;
            int da = 1;
            FillSpiral(y, x);
            while (y < maxY && x < maxX)
            {
                for (int i = 0; i < da; i++) FillSpiral(--y, x);
                for (int i = 0; i < da; i++) FillSpiral(y, ++x);
                for (int i = 0; i <= da; i++) FillSpiral(++y, x);
                for (int i = 0; i <= da; i++) FillSpiral(y, --x);
                da += 2;
            }
        }

        void FillSpiral(int y, int x) { }
knotty sun
#

start 0,0 would not make a lot of sense, that is the top corner of the grid

vague slate
#

It's not really for me

#

since those are just offsets

#

meaning I can go negative

knotty sun
#

then you need to converr that to an array position because an array cannot have a negative index

vague slate
#

all I need rn is just offset array

#

so smth like

#

[0,0;0,1;1,1;1,0 ..]

#

so then I can use actual center position

#

and simply do pos += offsets[i] in for loop

#

to get offset spiral position of grid

knotty sun
#

you can transform the y and x to anything you want in the FillSpiral method

vague slate
#

seems correct

#

allthough I'm confused on maxY and maxX

#

because I got 1k elements

#

or is that how many I'll get

#

wait

knotty sun
#

those are the radius of the spiral

vague slate
#

16 x 16

#

oh wait

#

it's 32 x 32

#

and it is 1k

#

holy

alpine coral
#

So I'm creating a 3D game where I want the player to be able to rotate on the x and y axis. I can get them both to rotate independently, however when they are combined, the rotation gets weird. I think its because when rotating on the y axis it takes both the horizontal input and vertical input even though it shouldn't.
Code: https://hatebin.com/pgvvhszrbq

knotty sun
alpine coral
#

what should I use instead?

knotty sun
alpine coral
#

I'm sorry, I'm not sure what you mean by that

knotty sun
#

it means that instead of relying on getting the euler angles from transform.rotation. you keep track of them in your own variable

alpine coral
#

so like 'Vector3 Rotation = transform.eulerAngles'?

knotty sun
swift falcon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    [SerializeField] private GameObject target;
    [SerializeField] private float offSet;
    [SerializeField] private float smoothTiming;
    [SerializeField] private float minZoomOut;
    [SerializeField] private float maxZoomOut;
    [SerializeField] private Vector3 YTurn;
    [SerializeField] private float maxYTurn;
    [SerializeField] private float minYTurn;
    float xMouse;
    float rotateX;
    float yMouse;
    float rotateY;
    float mouseScroll;

    Vector3 currentRotation;
    Vector3 velocityVector = Vector3.zero;


    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }
    private void Update()
    {
        

    }
    void LateUpdate()
    {
        xMouse = Input.GetAxis("Mouse X");
        rotateX += xMouse;


        yMouse = Input.GetAxis("Mouse Y");
        rotateY -= yMouse;
        rotateY = Mathf.Clamp(rotateY, YTurn.x, YTurn.y);

        mouseScroll = Input.GetAxis("Mouse ScrollWheel");

        offSet -= mouseScroll;
        offSet = Mathf.Clamp(offSet, minZoomOut, maxZoomOut);
        transform.position = target.transform.position - transform.forward * offSet;
        Vector3 targetRotation = new Vector3(rotateY, rotateX, 0);
        currentRotation = Vector3.SmoothDamp(currentRotation, targetRotation, ref velocityVector, smoothTiming);
        transform.eulerAngles = currentRotation;



    }
}

Hello guys, I don't know why but my camera is shaking as i showed in video. How can I fix it? It's my camera script.

swift falcon
#

or I'd like to know the real problem

unkempt pelican
#

Hey there! Not sure where to ask this, but I was wondering if anyone knows any resources that I could check out that helps with making the game window an object that interacts with the game. Stuff like moving the window would make liquid in the game slosh around and such. If this isn't the place to ask, I'd love to know where I should direct this question! Thanks for any advice in advance!

rigid island
rigid island
#

after that is just a matter of relaying that back to unity as input

unkempt pelican
knotty sun
rigid island
#

but yeah on windows is way easier

errant flame
#

Is there any way I can take a high res screenshot of any editor window (not game view) ?

west lotus
#

So I'm having a strange issue. I have the following set up in an animator. Idle -> Put Weapon away -> Put new weapon up -> idle. The transition from idle to put away is controlled by a trigger ChangeWeapon. away to up just has an exit time. If I manually click the trigger in the animator everything works. However setting the trigger from code like so HandsAnimator.SetTrigger("ChangeWeapon"); plays the away animation about halfway before getting interupted and snaping back to idle. Wtf ?

#

if I use a bool it all works as well

#

fuck me must be another animator bug....

low spear
#

In Unity Mathematics, is it possible to "scale" a quaternion. I'm storing a quaternion to represent an objects orientation, and another quaternion that represents its rotation rate... I was hoping to do _currentRotationQuat += _rotationRateQuat * deltatime; But I can't seem to scale the quaternion with a float no matter which way around I write it. Is this possible?

late lion
knotty sun
leaden ice
#

slerp(quaternion.identity, myRotation, 0.1f) is 1/10th of myRotation

low spear
#

Right, thanks all, will give these a go!

#

yep, that's working now! thanks!

torn kite
#

Can someone help me lower my unity batches

tawny elkBOT
west lotus
torn kite
#

Im using defaut render pipeline

#

i just get liek 8k for no reason

#

i wish someone would join call and just diagnoise why but apparently i cant ask that

west lotus
#

Well a good way to diagnose this type of problem is to start turning off chunks of the level and see how the batch count changes

somber nacelle
#

can also use the frame debugger

merry stream
#

are there any issues with this that could possibly lead to json corruption/overwriting? very rarely my save will just wipe and I can't figure out why or whats causing it. The only thing I can think of is some issues with unity play mode after editing scripts (saving script while still in play mode causing a bunch of errors). I haven't tested it enough in build to see if the issue occurs there or what could even be causing it

simple egret
#

The stream manipulation to create the file here is definitely not pretty - either use the stream to open, write, close in one go, or don't use it at all

merry stream
#

im not super experienced with handling files with c#, can you explain what I could do better?

simple egret
#

You can use a StreamWriter to wrap the stream, then call Write(json); NewtonSoft Json might even have an overload to take a Stream and directly write the JSON to it

merry stream
#

okay, would that be whats causing the issue?

#

if not, how could I check if the data trying to be saved is corrupted and to not delete the file, because I believe that's whats happening

#

its just writing an empty file

soft shard
merry stream
#

this is my load function, maybe some issues here?

simple egret
errant flame
simple egret
simple egret
#

That works - put the using line inside the try block to catch file creation errors though

merry stream
#

does Write overwrite the file?

#

or append

simple egret
#

Also use Path.Combine(Application.persitentDataPath, localPath) to build the path in a cross-platform manner

#

It overwrites, as specified by the File.CreateText() documentation

If the file already exists, it is overwritten

merry stream
#

great thanks