#archived-code-general

1 messages · Page 453 of 1

night harness
#

like it would just be a straight up fork of cc

#

24 / 33 classes in the unity 6 cc package reference the entities package

round violet
#

lol

junior yew
#

Anybody here uses the "experimental" graph package / library? I remember reading that it was getting an update. Is it coming in 6.2 or "soon"?

placid summit
#

I wanted a runtime node graph library, I found one as a starting point but comes with a minimal starting set of options/nodes

tough carbon
#

how could I draw graph for UI? Is it possible to make it with UI toolkit? I found out only about Vector API, but I am not sure is this the best option

tough carbon
vestal arch
#

<@&502884371011731486> either scam or advertisement, your pick

thick terrace
dense estuary
#

As of now, my game's scripts are heavily linked together. For scripts that only exist once, would it be better to make them serializable and reference themselves as a public variable?

Like this:

[Serializable]
public class HealthSys : MonoBehaviour
{
    public HealthSys healthSys = this;
}
#

So other scripts can just do HealthSys.healthSys.health = 50 or something.

leaden ice
#

google Unity Singleton

#

you will find real working examples of how to do it

dense estuary
#

Would a Singleton be bad for a single player health system? Everywhere I look says yes.

vestal arch
#

well, depends on what you mean by "bad"

dense estuary
#

I feel like other classes being able to access the health without a direct reference would be good.

vestal arch
#

i don't think it'd be bad in itself thonk
it's just that there are better alternatives, depending on your exact needs

#

you could, for example, have the player controller be a singleton and have health managed directly by the player controller

#

or you could have a more modular system that also handles enemy health

dense estuary
#

I have a player class that acts as the core of the player, so I could do that instead.

leaden ice
dense estuary
#

Examining my code, I found that my stamina system directly references the movement class, and the player class references both the stamina and movement. I feel like there's an unnecessary reference.

potent aspen
#

I've got a general item class for a inventory system, how would you guys handle adding behavior to items?

#

like a sword does damage, a health item heals, a potions contains an effect

leaden ice
#

a really siomple way is for the item class to just have an enum on it, and then you use a switch statement to do the different behaviors

#

the most complex way would basically be to have a mini scripting engine and the item references a script that will run

#

and you can have many things in between

potent aspen
#

ah okay yeah

#

thought about something like that

#

I'm used to either custom engines, the creation engine or godot so I just wanted to know if there was some... hidden magic bullet in Unity, there often seems to be lol

leaden ice
#

The problem is that "items" and "item systems" range dramatically in how complicated they are, and also the way they interact with the rest of your game of course depends oin how the rest of the game is structured

#

there won't be any silver bullets here unfortunately

potent aspen
#

yeah that's fair

#

I'm gonna go... consider how to do it (before implementation so I don't screw myself), thanks!!

sweet raft
#

A fresh set of eyes might help. Does anyone see any way this might be triggering an infinite loop? Or any other way to hang up Unity?

public class Test : MonoBehaviour
{
    public GameObject prefab;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        Vector2 spawnOffset;
        Vector3 spawnPosition = new Vector3();
        Collider[] Colliders;
        Pokemon p;
        int tries;

        spawnOffset = Random.insideUnitCircle * 50;

        for(int i = 0; i < 10; i++)
        {
            tries = 0;

            do
            {
                if(tries > 10)
                    break;

                spawnPosition = new Vector3(transform.position.x + spawnOffset.x, transform.position.y, transform.position.z + spawnOffset.y);
                //spawnPosition.y = Terrain.activeTerrain.SampleHeight(spawnPosition);

                Colliders = Physics.OverlapSphere(spawnPosition, prefab.GetComponent<CapsuleCollider>().radius * 5.0f);
            }
            while(!Utilities.IsNullOrEmpty(Colliders));
            
            if(tries > 10)
                continue;
            else
                Instantiate(prefab, spawnPosition, new Quaternion());
        }
    }
}
latent latch
#

First place to look is your while loops

vestal arch
#

you have that if (tries > 10) break; but you never actually increment tries

sweet raft
leaden ice
#

a safer formulation would be a for loop. for (int tries = 0; tries < 10; tries++)

latent latch
#

Probably could just use another forloop

leaden ice
#

then let the !Utilities.IsNullOrEmpty(Colliders) condition be the early out

vestal arch
#

you're also not using i in the loop? so not sure what the point of the early abort is for, since you'll just try again another 10 times

leaden ice
#

new Quaternion() < this also does not produce a valid Quaternion (unfortunately). You need Quaternion.identity

sweet raft
tall gazelle
#

Is anyone here familar with how the Quick Outline store asset works? I'm trying to figure out how to exclude some objects from adding a silhouette fill to the object with the outline script when they're occluding it.

latent latch
#

Probably stencils. Looks like stencils so shader related

untold stirrup
#

Hi, is there a way to change the animator's avatar from code during runtime? I've been trying, but it doesn't animate until I make some changes in the inspector, such as disabling and enabling the animator

floral drum
#

is their anyway to make it so nav mesh obstacles dont "push" around agents, and instead they pathfind off of it when they are on it

rocky steppe
#

How helpful is the Unity Learn Junior Programmer course?

leaden ice
#

very helpful if you're a beginner who knows nothing about Unity

#

not that helpful if you're not.

rocky steppe
#

I'm a intermediate programmer in Java, I came to Unity a couple weeks ago, and I've been learning C# and have converted my knowledge from Java To C#

#

I have little to no experience with Game Engines such as Unity.

leaden ice
#

it's helpful to understand how your code interacts with the game engine

dawn nebula
#

In Unity, I'm trying to use an interface to define behavior for multiple visual components. I want to assign these components in the Inspector and store them in a list, but since Unity doesn't support serializing interfaces, I'm forced to either:

  1. Use abstract Monobehaviour classes.
  2. Expose a Monobehaviour field, cast to the interface in Awake and store it in some other field.

Which is more standard?

late lion
leaden ice
chrome trail
#

I'm trying to research how to make a save system and, I have to ask, how would you normally handle small events like an NPC giving you an item and the game remembering the NPC already gave you an item so they won't do it again? Surely it's not something you heap into one big Game Data structure, right?

#

Because all the tutorials I'm seeing seem to just be doing that as their save system

leaden ice
#

That goes in a list

#

You might have a list of one off events or a list of quests with a number for how many stages of that quest you completed.

chrome trail
leaden ice
#

Idk about that other stuff I'm talking about just the NPC interaction part

#

But yes always one big object representing the state of the game

chrome trail
#

Ah, so that's just unavoidable then

leaden ice
#

In the case of a larger game like an MMO it may be structured more like (and indeed actually use) a relational database. But if you're talking save file then it should all be one object.

chrome trail
sudden ruin
#

trying to up my garbage code with some design pattern in some random projects
anyone had done or know this customization feature before can suggest me your design approach ?

cosmic rain
tepid oar
#
IEnumerator PassiveIncomeRoutine()
{
    while (true)
    {
        TotalincomeperInterval = IncomePerInterval * buttonincomescript.IncomePerProd;
        yield return new WaitForSeconds(interval);
        AddPoints(TotalincomeperInterval);

    }

}
#

my TotalincomeperInterval stops working when i multiply it with IncomePerProd even when IncomePerProd is set to 1

vale walrus
tepid oar
#

no

#

just in this line of code

deep stirrup
#

Hello, I am creating an FPS game and my player is based on CharacterController, but I also have moving walls that will push player, so what is the correct way to do this? My wall just passes through player for some time, and when it's halfway in player, CC just get instantly pushed out, and when the wall is moving to fast, it just passes right through! I tried using different move methods, like Rigidbody.Move() with Continuous collision methods for walls, but nothing works 😦

fringe parrot
#

Hi. I have a problem with my first person movement where the character automatically rotate when colliding with something. you can find the script and the problem in the video

cosmic rain
deep stirrup
cosmic rain
cosmic rain
deep stirrup
deep stirrup
cosmic rain
#

Obviously, you can't - it's a feature implemented in the CC. But you can implement your own.
@deep stirrup

fringe parrot
#

but I don't think it is the problem. the problem happens once I collide with something. I tried increaing Angular damping and it reduced the rotation a little

leaden ice
cosmic rain
fringe parrot
fringe parrot
deep stirrup
cosmic rain
# fringe parrot not currently. but I will

Ok, I'd still try commenting out that rotation code just to be sure.
And then also check if you have any extra colliders on your character or parented to it, that could be aplying torque to the character.

deep stirrup
cosmic rain
fringe parrot
deep stirrup
cosmic rain
fringe parrot
#

it worked. Thanks again sadok

cosmic rain
upper karma
#

public void SpawnEnemies(int Level)
    {
        if (Level == 1)
        {
            StartCoroutine(Level1());
        }
    }


    public void SpawnEnemy(GameObject Enemy, Transform Location)
    {
        Instantiate(Enemy, Location);
    }

    IEnumerator Wait()
    {
        yield return new WaitForSeconds(2);
        SpawnEnemies(1);
    }


    IEnumerator Level1()
    {
        //SpawnEnemy(Dronepf, //create new Transform idk());
        yield return new WaitForSeconds(2);

    }

is this correct?

vestal arch
#

define "correct"

#

does it work?

chrome trail
cold parrot
chrome trail
cold parrot
cold parrot
delicate granite
#

hello people!
i have an issue, believe it or not, where counting decides to go to 0 instead of the assigned number.

simple blackjack game really with an ai.

(screenshot of unity seeing an 8 and a 3 and it still being 0)
(second screenshot of value not being 0)

the code and all of the information regarding in pastebin: https://pastebin.com/sUkRpwLY

vestal arch
leaden ice
delicate granite
#

alr. its in a messy state which i'll clean up but i'll grab all of them real quick

leaden ice
#

it's also not clear to me why your CountCards() method both returns a value and also ... seems to set this total variable which is for some reason not a local variable?

#

there's some fishy stuff going on there

delicate granite
#

yeah i think i got confused there

leaden ice
#

You should also log additional stuff like:

  • how many cards are in the cards list/array
  • what the value of each card is as you see it
#

e.g.

int CountCards() {
  int total = 0;
  Debug.Log($"Checking {cards.Count} cards"); // If it's an array it'd be cards.Length
  foreach (var card in cards) {
    var cardValue = card.GetComponent<CardHandler>().value;
    Debug.Log($"Saw a card with value {cardValue}");
    total += cardValue;
  }

  Debug.Log($"Total is {total}");
  return total;
}```
delicate granite
#

stupid question, cards is an array, for me, Count does not come up as an option. how do I go about doing this?

leaden ice
#

I just added a comment for that

#

For arrays it's Length not Count

delicate granite
#

ohh thanks

#

so it's going like this:
(the top one says hit too)

#

that was pressing hit once. the card for the ai is 4

leaden ice
#

Toggle this off

#

but it seems like probably all the cards have a value of 0

delicate granite
leaden ice
#

why is it only printing "Card w/0 value" one time

delicate granite
#

they're not supposed to

leaden ice
delicate granite
leaden ice
delicate granite
#

yeah the one card

leaden ice
#

you have 5 nulls

#

and one card

delicate granite
#

yeah

leaden ice
#

so - you're going to get an error

delicate granite
#

i clicked hit once

delicate granite
# leaden ice so - you're going to get an error
 Debug.Log($"{cards.Length} cards");
                foreach(var card in cards)
                {
                    if(card != null)
                    {
                        var cardVal = card.GetComponent<CardHnadler>().value;
                        Debug.Log($"Card w/ {cardVal} value");
                        total += cardVal;
                    }
                   
                }
                Debug.Log(total);
#

oh my god

#

ah supposed to be in the foreach loop

leaden ice
#

ok I didn't know you had this if (card != null) bit

delicate granite
#

sorry i was supposed to say

leaden ice
#

oh right it was there in your snippet before

#

anyway it really just seems like you are referencing a different Card (clone) object than you think you are

#

either that or the value is getting set on it AFTER you run this code

delicate granite
#

you know what, i think maybe it is running after

#

because it instantiates the card and instantly adds it and counts it i believe

#

in cardhandler, instaed of using start, would awake be betteR?

leaden ice
#

yes

#

Start runs much later

#

Awake runs by the time Instantiate returns

#

you didn't show the code before that was setting the value

delicate granite
#

oh my bad

#
public class CardHnadler : MonoBehaviour
{
    [SerializeField] TMP_Text cardNum;
    [SerializeField] GameManager gm;
    public int value;
    
    void Awake()
    {
        if(gm == null)
        {
            gm = FindFirstObjectByType<GameManager>();
        }
        do
        {
            value = Random.Range(1, 12);
        }
        while (gm.cardNumbers.Contains<int>(value));

        gm.cardNumbers[value - 1] = value;
        
        cardNum.text = value.ToString();
    }
}
leaden ice
#

yeah - if that was Start before it would not have run by the time you were calling CountCards if it was just instantiated then

delicate granite
#

yeah, it works now but i think i've done something stupid

#

apparently 8 + 11 is 38

#

or maybe its adding up all the cards on the table

#

yeah it is

#

thanks for the help! i'm gonna try and fix this now

opal kettle
#

Hey folks, I'm a beginner to Unity and C# (but not programming in general), and I've been learning gamedev by working on a 2D platformer

I’ve been watching some talks (like Ryan Hipple’s on ScriptableObjects) that promote a more event-driven approach to game architecture, avoiding singletons and pushing for loosely coupled systems. I can see the benefits in theory, but in practice, I’m finding this style of architecture really difficult to wrap my head around. It feels like it’s slowing me down a lot—probably just due to the learning curve

My question is: for people with more experience, was it worth putting in the time to get good at this kind of architecture early on? Or should I focus more on just getting things working, even if that means leaning on things like singletons or more straightforward patterns for now?

steady bobcat
#

Singletons can be useful but makes users less flexible in how they are used. In games I work on I use static stateless helpers and services and pass dependencies manually and make do

vestal arch
#

focus on getting something working before getting something good - of course that doesn't mean using bad patterns on purpose, you can use your prior experience to your advantage

lean sail
# opal kettle Hey folks, I'm a beginner to Unity and C# (but not programming in general), and ...

scriptable objects as events are pretty bad imo and it isn't neccessary for an "event-driven approach". All it does is move your event to exist on a SO. Suddenly you're creating a whole asset everytime you want a new event. This doesn't work too well if you want a dynamic number of events either and you'd have to suddenly create SO instances at runtime, not ideal.
Ask yourself, why avoid singletons or care about loose coupling. If you're only supposed to have one instance of something, a singleton solves that. Your game is going to be tightly coupled at the end of the day pretty much no matter what you do, because your game is designed to work with itself. Moving logic from one file to another or adding another layer of confusion doesn't change that.

opal kettle
steady bobcat
#

Not something difficult to solve

#

I am working on a game rn that needs something like this, 1 component handles ticking sub components and passes a list of all objects to them which is used to find ones in range.

opal kettle
# lean sail scriptable objects as events are pretty bad imo and it isn't neccessary for an "...

True. But for bigger games, are singletons still good enough? From the talk I mentioned, in larger systems a more modular design is said to be beneficial since you can just drag prefabs into your scene and not worry about needing to bring in singletons, which would also need other singletons to be brought in, and ending up bringing a ton of game objects in your scene just for a single prefab. This might be a little bit over exaggerated tho, but for the most part I'm trying to figure out whether or not I should care about these things at the beginning

And yes, I've got to agree, when it comes to creating events at runtime it starts to feel a little awkward using scriptable objects

lean sail
#

Yes a singleton is fine for your game. The whole singleton part quite literally is just a way to reference your instance. Nothing here changes what the user sees, or how the game runs

steady bobcat
#

For some beginner project its not going to matter. If you need to maintain a medium to large project long term it needs to be designed in a sane way

#

if you have loads of rando events with no clear relationships it will be a pain in the ass to debug or for anyone to maintain later

#

(a big reason why i avoid doing inspector unity event subscriptions as much as possible)

opal kettle
#

Alright, I think I have a clearer vision to doing this now. It's basically to make the thing work and also care about the code architecture once the projects hits a reasonable size to have maintenance issues

#

Thanks @lean sail @steady bobcat

floral drum
#

so is their like any good fix to players cameras stuttering? its only noticable when im moving and rotating my camera but ik its because im doing my movement in fixedupdate

vestal arch
#

is your camera movement in lateupdate?

floral drum
#

yes

#

well i just move the camera to where the rb is

lean sail
vestal arch
#

does your rb have interpolation

floral drum
#

yes i have it on interpolate but its still rlly noticable, like when im moving and trying to track targets it just looks really stuttery

leaden ice
#

this will happen if your code is modifying the Transform directly

#

very common pitfall

#

the solution is to never modify the Transform of your Rigidbody directly. Only through the RB

floral drum
#

rb.transform.localRotation = Quaternion.Euler(0, MouseHorizontalInput, 0);
like this

leaden ice
#

that will break interpolation

floral drum
#

geez, so what would i need to do add torqe to make the characters rb turn?

leaden ice
#

no

#

just rotate the RB

#
rb.rotation *= Quaternion.Euler(0, MouseHorizontalInput, 0);```
floral drum
#

sweet, great call i appreciate it

neon current
#

I've been working on coding a game that has multiple different playable nonhumanoid characters. I really want to make the movement for each one different so that you feel like you are the character. Like moving your head to aim where you are going as a snake. However I also want attack actions (like lunging forward as a snake somehow) and magical abilities.

My question is, do y'all think that from a coding perspective that would be too much of a nightmare to make an enjoyable experience?

dawn nebula
#

If I have two of the same component (Let’s say a Health component) on a gameobject, and try to have another script reference these components by dragging them into the inspector, how do I specify which of the two components to reference?

sacred totem
#

Is it normal for Unity to lag whenever I load a new scene for the first time?

neon current
#

Like you should be able to drag the component itself instead of the game object

leaden ice
#

By right click on it and select properties

#

Then you can directly drag the components

dawn nebula
void basalt
#

Has anyone ever done a true OOP inventory where all of your storable types inherit from a base "Item" class? And you literally store whole real objects?
Did memory usage ever become an issue?

dawn nebula
void basalt
#

People in this community like to use scriptable objects for doing inventories afaik

#

like you just store limited data about whats actually in your inventory

#

and instantiate gameobjects in/out when you drop/pickup items

wicked scroll
#

the thing is that an inventory isn't really anything...it's essentially an array, so what is that abstraction gaining you? it sounds like your actual question is 'what if all my items inherit from a base Item class' which I'm sure is not uncommon

void basalt
#

what is that abstraction gaining you?
proper usage of object oriented programming is what im gaining

#

where I can just do inv[0].Use();

#

and call it a day

wicked scroll
#

seems like your inventory is not very OOP if you are reaching into it by index

void basalt
#

why not?

wicked scroll
#

because you have no inventory object (class*)

#

anyway if you want your items to inherit from some sort of abstract item class, sure that's reasonable

dawn nebula
fast hazel
#

!ide

tawny elkBOT
sudden ruin
#

has anyone used dotween ?
im tweening projectile position to a target, but doMove only take a given time to reach target and since the distance is varied the result is project goes slow when target is close fast when far, i want to give in a given speed rather than a time to reach target
i want to know if dotween support a way around this? or how you guys did this

mellow sigil
#

The easiest way is to just use normal MoveTowards

#

If you want to use Dotween you'll have to calculate the duration yourself which is distance / velocity

sudden ruin
#

yea i was trying to avoid calc distance, i really hoped dotween would support this simple moving at constant speed. like i miss in the docs or a way combining options together something

#

movetoward could work but dotween can do chaining other stuff that really handy

sudden ruin
#

fr thanks

vestal arch
#

seems like i can't link directly to it

#

search for "speed" in that page

rocky arch
#

Is there a way to make ui toolkit elements not interactable - purily visual and would not block other UI or UI toolkit elements from being interacted with ?

Wrapper.pickingMode = PickingMode.Ignore;

doesnt do antyhing

honest tangle
#

anyone decent at using quaternions for main camera rotations ?

mellow sigil
#

Very few people are. Thankfully everything can be done with the helper functions so you don't need to be

maiden fractal
quartz folio
honest tangle
#

however with my current code, it for some reason rotates correctly during my while loop for the rotation, then at the last moment it snaps back to the original rotation

maiden fractal
honest tangle
#

not at home rn but can send u after

maiden fractal
#

please do

tawny elkBOT
honest tangle
#

I've been using Claude to help me out i understand the general concepts

young yacht
#

each item inventory could have a IUsable interface

#

you call it and do whatever with it

#

such as Use()

manic fox
#

Hi there its my first time chatting and I could really use some help 🙏

hidden compass
#

!ask

tawny elkBOT
hidden compass
#

last bullet point, being the important one to ask

manic fox
#

sorry im just trying to see if my code isnt too long to send

#

one sec

hidden compass
#

u can use external paste bins for long !code

tawny elkBOT
manic fox
#

https://paste.mod.gg/ebupcunmugyh/0

im trying to get this grid system to work in a vr environment. My idea was to attach a raycast from a prefab unto a grid. So far i cant figure out how to have the ray to interact with the grid.

https://www.youtube.com/watch?v=l0emsAHIBjU&list=PLcRSafycjWFepsLiAHxxi8D_5GGvu6arf&index=1

In this Unity 3D tutorial start creating a Grid Building System. First we will use Grid component to calculate a cell position for our mouse pointer position to use it in our placement system. Next we will expend the system with a custom grid shader and an object placement and removal system. At the end of this tutorial you will have a grid plac...

▶ Play video
#

heres the vid im using as reference as well

hidden compass
#

whats the exact issue? u cant get a raycast to detect em?

leaden ice
manic fox
#

My main issue is that I cant call the Ray cs to the Input manager. I tried to call it like this

#

but i get this error

manic fox
leaden ice
#

seems unlikely

#

Also: Vector3 mousePos = transform.TransformDirection(Vector3.forward); this seems incorrect as well

#

shouldn't you be incorporating the mouse position in there somehow?

leaden ice
manic fox
#

No cause im developing this for vr (excuse the variables i ripped them from the video i was watching sorry)

manic fox
leaden ice
#

It sounds like you're trying to adapt the tutorial to a totally different situation than the tutorial was made for

#

tutorials are meant to be copied verbatim to learn concepts

#

you are trying to skip the "learn the concepts" stage it seems

#

you won't be able to adapt the tutorial to your game without understanding how it works.

manic fox
#

alright I get what youre saying

#

ill try to learn more

hidden compass
#

but yea.. i think u need some more basics.. and/or to move over to beginner-code

leaden ice
#

transform.forward is a world space vector
Vector3.forward is... basically unspecified. It depends which context you use it in.

hidden compass
#

ahh true.. mb.. ya transform.forward (global vector) representing the forward direction of the transform
edit: i haven't seen fwd in a very long time 👀

hidden compass
reef garnet
#

What approach does everyone take to pausing the Physics system, when pausing the game? I'm looking for a method that does not rely on editing the timeScale, I've got everything working except physics

reef garnet
#

nevermind, just found the best way to do it with seemingly no downsides

    public void SetGamePause(bool value)
    {
        isGamePaused.Value = value;

        Physics.simulationMode = value ? SimulationMode.Script : SimulationMode.FixedUpdate;
    }
#

additionally you can then create a custom physics update script when paused maybe setting everything to super slow motion

steady bobcat
reef garnet
#

it's a scriptable object acting as a bool variable

steady bobcat
#

Right, guess that works but seems overkill for 1 var

#

and depending on how its loaded it can loose its value if unloaded then reloaded

reef garnet
#

well every object that I want to be paused, has a reference to that object, the object has an OnValueChanged Event so I can trigger pause/unpause behaviour

pale oxide
#

Does anyone have any FPS movement code?

#

I dont really care as long as it has jumping, walking, and sprinting

night harness
#

We don’t do that here

vestal arch
#

the internet has plenty

reef garnet
night patio
#

does anyone have a simple shared memory IPC guide?

fiery steeple
#

are bools initialized at "false" by default or null ? Because my editor says it's useless to set the value to false by default value is redundant 🤔

steady bobcat
void basalt
night patio
#

importing them directly into Unity raises some errors i cant troubleshoot

#

so im using IPC because i know c# console project work perfectly

#

also i already got a shared memory IPC going well, but thanks for the reply

sweet raft
#

Any idea why this callback wouldn't be getting fired?

m_playerInputActions.Controls.Throw.performed += Throw;

The method...

private void Throw(InputAction.CallbackContext obj)
{
    Debug.Log("Throw performed.");
    m_characterMotor.ThrowBall();
}

Attached a screenshot of the Input Actions.

latent latch
#

did you enable your input action asset

sweet raft
#

Yep.

#

The Movement works just fine.

latent latch
#

I'd try using Started over performed, otherwise probably some setting in the action properties there

leaden ice
#

Also any errors?

sweet raft
#

No errors and code's too long for Discord so I tossed it in a notepad file.

#

I think... I think when I just C&P'd it I see the problem...one sec.

#

Yeah I got it. During some point somebody got rid of actually calling EnterPlayerInputMode().

mild goblet
#

has anyone had the problem where handles work once after recompiling in runtime, then dont work in runtime afterwards?

tawny elkBOT
round violet
#

most of the time when i attach a debugger to the editor on rider, i get stuck in a infinite reloading domain, any ideas why ?

latent latch
#

You sure you've not hit a breakpoint?

vestal arch
# fiery steeple are bools initialized at "false" by default or null ? Because my editor says it'...

to expand: default default values tend to be the equivalent of "all zeroes" (all 0 bits) for that type
for integrals and floating-points, that's the value 0
for booleans, that's false
for chars, that's \0, the null character
for reference types, which are basically pointers, that's null - a null pointer
for structs, you basically get each member 0-initialized - that might become an issue if you have to implement something where all-zeroes is not necessarily a valid state, for example a rational number type, so keep that in mind

fiery steeple
#

I have another question :
Is there a premade method in C# / Unity to turn a 2D array into an array (1D) please ?

vestal arch
#

i don't think so

#

there are linq solutions to flatten an array of arrays (or well any enumerable of enumerables) though (just as an aside)

#

doesn't seem too hard though

#

(what are you trying to do btw)

fiery steeple
# vestal arch (what are you trying to do btw)

I'm doing Minesweeper, and I already have the Grid generated with all the "Tiles" gameObject generated but they're inside a 2D array, and now I need to copy that 2D array and make it into a 1D array to select random locations to spawn the mines and retrieve that location from the List

vestal arch
#

why do you have to make it a 1d array?

fiery steeple
vestal arch
#

wdym?

#

oh with what, Random.GetItems?

#

wait no unity doesn't have that

fiery steeple
vestal arch
#

well if you're already indexing the array yourself, it really isn't that hard to index a multidimensional array with random values

#

you could either randomize each dimension, or randomize the cell and calculate each dimension

fiery steeple
fiery steeple
vestal arch
#
Cell[,] grid;

// option 1
int y = /* random in [ 0, board.GetLength(0) ) */
int x = /* random in [ 0, board.GetLength(1) ) */
Cell cell = grid[y, x];

// option 2
int index = /* random in [ 0, board.Length ) */
int y = index / board.GetLength(1);
int x = index % board.GetLength(1);
Cell cell = grid[y, x];
fiery steeple
vestal arch
#

it's basically just reversing the operation you'd do to store a 2d index as a single number

#
2d coords (3x4)              as single indices
+-----+-----+-----+-----+    +-----+-----+-----+-----+
| 0,0 | 0,1 | 0,2 | 0,3 |    |   0 |   1 |   2 |   3 |
+-----+-----+-----+-----+    +-----+-----+-----+-----+
| 1,0 | 1,1 | 1,2 | 1,3 |    |   4 |   5 |   6 |   7 |
+-----+-----+-----+-----+    +-----+-----+-----+-----+
| 2,0 | 2,1 | 2,2 | 2,3 |    |   8 |   9 |  10 |  11 |
+-----+-----+-----+-----+    +-----+-----+-----+-----+
```if we treat the coords as `y,x`, you can see that the single index for each cell is `y * 4 + x`
it's basically saying - for each row, add 4, then add the column
each row is 4 steps, then the remainder is how far you step for columns
#

so with the division, since it's integer division, you get just the row - 0,1,2,3 / 4 -> 0, 4,5,6,7 / 4 -> 1, etc
then with the modulo, you get the remainder, just the columns

#

higher dimensions can use the same logic but it'll look a bit more messy lol

#

iirc ive done this with 4 dimensions before

fiery steeple
#

you're crazy 😄

vestal arch
#

for some index i over a n-dimensional array d_1 ... d_n
i_1 = i / (d_2 * d_3 * ... * d_n)
i_2 = i / (d_3 * d_4 * ... * d_n) % d_2
i_3 = i / (d_4 * d_5 * ... * d_n) % d_3
...
i_k = i / (d_k+1 * d_k+2 * ... * d_n) % d_k
...
i_n = i % (d_1 * d_2 * d_n-1) % d_n

i = (...(((i_1 * d_2 + i_2) * d_3 + i_3) * d_4 + i_4) ...) * d_n + i_n
or:

i = 0
for k in 1 -> n:
  i *= d_k
  i += i_k
regal crag
#

how to make transform relative to a specific location, so that it always applies the relative transform despite the orientation? (right is target Vector3, left is reference location, both initial)

regal crag
vestal arch
#

i spent way too long figuring that out

regal crag
#

I'm studing some of this right now but I suck at it

vestal arch
regal crag
#

like a math equation that you can pass such that you get the offset location

vestal arch
#

well it's what would achieve "make transform relative to a specific location"

#

if you only care about its position at some point in time, you could use TransformPoint iirc

#

that would also take into account rotation and scale iirc

#

if you only need the position, it'd be as simple as adding the positions together

regal crag
#

bc that broke and didn't work for me

vestal arch
#

if you need to inherit rotation as well, then use TransformPoint

#

if you don't want to inherit scale, i guess you could do TransformDirection and then set the magnitude as needed? and then set the offset

regal crag
#

TransformPoint(transform.localposition + offset)?

vestal arch
#

reference.TransformPoint(transform.localPosition)

regal crag
#

doesn't seem to work

#

wait

#
        var castCameraLocation = playerCamera.transform.position;

        var castCenter = playerCamera.transform.TransformPoint(castCenterOffset);```
#

like this?

vestal arch
#

just for self-reference```
Transform r; Vector3 p;
| pos | rot | scale |
| | | | p
| | | / | Vector3.scale(p, r.lossyScale)
| | / | | r.TransformDirection(p)
| | / | / | r.TransformVector(p)
| / | | | p + r.position
| / | | / | Vector3.scale(p, r.lossyScale) + r.position
| / | / | | r.TransformDirection(p) + r.position
| / | / | / | r.TransformPoint(p)

vestal arch
regal crag
#

just an offset on the castCameraLocation expressed as the variable castCenter

vestal arch
#

considering both position and rotation?

regal crag
#

yes, I want to keep the origin and rotation of the castCameraLocation but apply a local transform relative to it

vestal arch
#

that's not what im asking

#

should the offset take into consideration the position and rotation of playerCamera

regal crag
#

yes, so the offset is always the same relative to the root playerCamera

vestal arch
#

then yeah that seems right

#

if not i suppose do some Debug.DrawLines

regal crag
#

lemme run debug rq

regal crag
gloomy hornet
#

Hello, I am trying to make a android gyroscope controller. I tried to use Input.gyro.rotationRateUnbiased, but it was that accurate. So i am trying to use Input.gyro.attitude.

private void Awake()
    {
        //Setting up the gyroscope.
        Input.gyro.enabled = true;
        startAttitudeSet = false;
    }
private void Update()
    {
        if (!startAttitudeSet)
        {
            startAttitude = Input.gyro.attitude;
            startAttitudeText.text = $"Start Attidude \n X : {startAttitude.x} / Y : {startAttitude.y} / Z : {startAttitude.z}";
            startAttitudeSet = true;
        }
        currentAttitude = Input.gyro.attitude;
        Vector3 calculatedRotation = new Vector3(currentAttitude.x - startAttitude.x, currentAttitude.y - startAttitude.y, currentAttitude.z - startAttitude.z);
        attitudeText.text = $"Current Attitude\n X : {currentAttitude.x} / Y : {currentAttitude.y} / Z : {currentAttitude.z}";
        calculatedRotationText.text = $"Calculated Rot\n X : {calculatedRotation.x} / Y : {calculatedRotation.y} / Z : {calculatedRotation.z}";
        transform.rotation = Quaternion.Euler(calculatedRotation);
        currentRotationText.text = $"Current Rotation\n X : {transform.rotation.x} / Y : {transform.rotation.y} / Z : {transform.rotation.z}";

        
    }

So basically I am trying to subtract the first attitude from the current attitude. When I write it down on the TMP_Text, it is correct. But when i try to use it on Quaterinon.Euler, it's not correct. Can somebody help please?

mellow sigil
#

The last text is printing quaternion elements. It should be $"Current Rotation\n X : {transform.eulerAngles.x} / Y : {transform.eulerAngles.y} / Z : {transform.eulerAngles.z}"

round violet
#

where can i get details on the errors of a build process ?
all i got is a few warnings and a "Build completed with a result of 'Failed' in xseconds (y ms) 13 errors"

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

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

Unity Hub

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

round violet
#

didnt found anything in the editor logs

tawny elkBOT
round violet
vestal arch
vestal hornet
#

Oh my bad!

vestal arch
#

i mean that is shader code right

vestal hornet
#

yeah

vestal arch
#

i don't know shaders at all so im not too confident in identifying that lmao

vestal hornet
#

ill delete my message as to not clutter the channel atwhatcost

dense shadow
#

hi

#

can someone help me with my script

#

im struggle how to add it

cosmic rain
tawny elkBOT
#

:teacher: Unity Learn ↗

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

dense shadow
#

but this is about runtime hierarchy reorder

#

@cosmic rain

cosmic rain
dense shadow
#

im making an runtime hierarchy for making 3d animator software in unity, i want to add reorder feature, but i cant do that

#

@cosmic rain

cosmic rain
#

!ask

tawny elkBOT
cosmic rain
#

Explain the actual issue. What does it mean "I can't do that"? Is there an error? What exactly are you trying to do(and how)? What debugging did you do so far? What are the debugging results?

dense shadow
#

i added drag and drop to the gameobject UI runtime hierarchy, it works, but not changing or set the sibling index

#

i that enought

#

sorry im bad in english

#

im not amerika

#

america

#

@cosmic rain

sudden zenith
#

good morning everyone! quick question if i just want strings to show on a scroll view is there a built in unity tool or do i need to make one?

cosmic rain
# dense shadow i that enought

No. It's not. Answer the other questions as well.
And please stop pinging me. If someone can answer your question they will.

Also, English is not my native language either. If you have difficulties communicating, use translators.

sudden zenith
#

like vertical scroll

cosmic rain
sudden zenith
dense shadow
#

Is that enough, the ui not following the sibling index or reorder because I don't know how in runtime

cosmic rain
round violet
#

anyone worked here on bullet hells ?
im moving each bullet using the transform.position each fixed update, then running a sphereoverlap command to check for hitted objects (faster than using colliders)
the issue is that even with a iteration time of 0.005ms per bullet, since i got around 1k-2k of them this takes 10ms to complete (at 2k)

in targeting mobile, so im unsure of the use of multithreading as this will consume the battery even more

steady bobcat
round violet
#

2k overlaps tests in less than 1ms

#

my bottleneck is my main loop running sync on GT

#

and yes im already user a layer filter

steady bobcat
#

You should only schedule x amount of overlaps then per frame but ideally we would do it all on another thread/in a job

#

ECS would perform better if say all bullets and overlaps were entities

round violet
hexed pecan
late lion
steady bobcat
#

Then cheat and split processing over different frames. Its what vampire survivors does (e.g. check xp overlaps every 4th frame only)

round violet
steady bobcat
#

wait are you making the main thread wait for its compleation?

round violet
hexed pecan
#

That's way less than 1ms 😁

steady bobcat
#

what is InitialUpdate() doing then?

hexed pecan
#

Oh i looked at the wrong number

round violet
#

but can IJobParallelForTransform be faster than 0.001ms ?

late lion
#

You should identify what is contributing most and optimize that first.

round violet
#

(thats how much time it takes to update a bullet transform)

late lion
#

I would expect it to be faster than 2.38 ms for 1938 instances, yes.

steady bobcat
#

transform changes require children to be made "dirty" too, how is this bullet set up?

late lion
#

Make sure the bullets are not under a shared parent object. Transforms update faster when they are in the root, especially for IJobParallelForTransform

round violet
steady bobcat
#

share code

round violet
#

lots of funcs, wait

steady bobcat
#

!code

tawny elkBOT
steady bobcat
#

Lets us look for other perf issues then if we can see it

round violet
#

some not important funcs body might be missing because i cleaned the file for you

#

FixedTransformMove on BulletEntity is just transform.position += transform.forward * (instanceParams.moveSpeed * Time.fixedDeltaTime); with the profiler marker

steady bobcat
#

I wonder if it would be better if you re use native arrays as much as possible as its not free to allocate and free

round violet
#

0.5-1.5ms

late lion
#

The total processing time went down by 0.5-1.5 ms? Or it is now 0.5-1.5 ms?

round violet
#

went down to 9ms instead of 9.5ms

round violet
#

instead of TempJob

steady bobcat
#

Yea, if they won't need to change size you can re use the same ones

round violet
#

i can create i once on first loop, clear on disabled
but i cannot resize it ?

steady bobcat
#

No so it would help best if you have an upper limit you enforce

round violet
#

maybe if i set it to 3k entries or something (this will never be reached) it may be faster ? idk

steady bobcat
#

Make some super big one just to test

round violet
#

ill test this tmrw thanks

honest tangle
# maiden fractal Would need to see the code to help further on that
IEnumerator ZoomToPosition(Vector3 targetPosition, float targetSize, float targetRotation, bool zoomingIn = false)
{
    isZooming = true;

    Vector3 startPosition = mainCamera.transform.position;
    float startSize = mainCamera.orthographicSize;
    float startZRotation = currentCameraZRotation; // Use tracked Z rotation

    // Get current X and Y rotations to preserve them
    Vector3 currentEulerAngles = mainCamera.transform.eulerAngles;
    float xRotation = currentEulerAngles.x;
    float yRotation = currentEulerAngles.y;

    // Handle rotation wrapping for smooth animation
    float rotationDifference = Mathf.DeltaAngle(startZRotation, targetRotation);
    float endZRotation = startZRotation + rotationDifference;

    float elapsedTime = 0f;

    while (elapsedTime < zoomDuration)
    {
        elapsedTime += Time.deltaTime;
        float progress = elapsedTime / zoomDuration;
        float curveValue = zoomCurve.Evaluate(progress);

        // Interpolate camera position, size, and rotation
        mainCamera.transform.position = Vector3.Lerp(startPosition, targetPosition, curveValue);
        mainCamera.orthographicSize = Mathf.Lerp(startSize, targetSize, curveValue);

        // Smoothly rotate only the Z axis, preserving X and Y
        currentCameraZRotation = Mathf.Lerp(startZRotation, endZRotation, curveValue);
        mainCamera.transform.rotation = Quaternion.Euler(xRotation, yRotation, currentCameraZRotation);

        yield return null;
    }

    // Ensure final values are set exactly
    mainCamera.transform.position = targetPosition;
    mainCamera.orthographicSize = targetSize;
    currentCameraZRotation = targetRotation; // Update tracked Z rotation
    mainCamera.transform.rotation = Quaternion.Euler(xRotation, yRotation, targetRotation);

    // Update zoom state
    isZoomedIn = zoomingIn;
    if (!zoomingIn)
    {
        currentZoomedSection = null;
    }

    isZooming = false;
}
#

so this is my function that is called when I press a specific spot on the screen. Whatever is inside the while function behaves as intended, it both zooms in (transformation) and rotates (rotation) properly. Then, in the final moment, the rotation goes back to its initial state prior to the while loop, while the transformation stays the same (and as intended)

#

What I am trying to do is - upon some onPressed action - to move the camera from point A to point B, which also involves rotation. If you have an easier implementation of this task in mind i'd gladly take it

#

I think the issue is that the code is using euler angles when I want to work only with quaternions

leaden ice
#

Why not just use Cinemachine 🤔

#

but yeah lerping individual euler angles is a recipe for disaster

#

Euler angles cannot be reliably dealt with on a compenentwise basis. They are a set of three, and can't be pulled out individually without bad stuff happening

#

I would recommend dealing with Quaternions only

vestal arch
#

there is a Quaternion.Slerp, isn't there

leaden ice
#

yep

#

Or just using Cinemachine

maiden fractal
#

Cinemachine absolutely, even DOTween (or similar) would likely be much easier

#

From what I remember from earlier, the code above is mostly AI generated right?

honest tangle
#

yep

leaden ice
#

Anyway you seem to directly be setting it back to the original rotation here, no?
mainCamera.transform.rotation = Quaternion.Euler(xRotation, yRotation, targetRotation);

#

So that feels... expected, with the given code?

honest tangle
#

the thing is that I tried removing everything after the while loop once prior, and it still behaved the exact same way

#

lemme try that again real quick just to see

leaden ice
#

because that other code is probably taking back over again once isZooming becomes false

honest tangle
#

this is my Update code: ``` void Update()
{
// Handle touch input for Android
if (Input.touchCount > 0 && !isZooming)
{
Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            HandleTouchInput(touch.position);
        }
    }

    // Handle mouse input for testing in editor

#if UNITY_EDITOR
if (Input.GetMouseButtonDown(0) && !isZooming)
{
HandleTouchInput(Input.mousePosition);
}
#endif
}```

#

i just refactored isZoomedIn to be isZoomed because isZoomedIn and isZooming looks way too similar

vestal arch
#

you're saying isZoomed and isZooming aren't similar?

honest tangle
honest tangle
#
{
    isZooming = true;

    Vector3 startPosition = mainCamera.transform.position;
    float startSize = mainCamera.orthographicSize;
    float startZRotation = currentCameraZRotation; // Use tracked Z rotation

    // Get current X and Y rotations to preserve them
    Vector3 currentEulerAngles = mainCamera.transform.eulerAngles;
    float xRotation = currentEulerAngles.x;
    float yRotation = currentEulerAngles.y;

    // Handle rotation wrapping for smooth animation
    float rotationDifference = Mathf.DeltaAngle(startZRotation, targetRotation);
    float endZRotation = startZRotation + rotationDifference;

    float elapsedTime = 0f;

    while (elapsedTime < zoomDuration)
    {
        elapsedTime += Time.deltaTime;
        float progress = elapsedTime / zoomDuration;
        float curveValue = zoomCurve.Evaluate(progress);

        // Interpolate camera position, size, and rotation
        mainCamera.transform.position = Vector3.Lerp(startPosition, targetPosition, curveValue);
        mainCamera.orthographicSize = Mathf.Lerp(startSize, targetSize, curveValue);

        // Smoothly rotate only the Z axis, preserving X and Y
        currentCameraZRotation = Mathf.Lerp(startZRotation, endZRotation, curveValue);
        mainCamera.transform.rotation = Quaternion.Euler(xRotation, yRotation, currentCameraZRotation);

        yield return null;
    }

    // Update zoom state
    isZoomed = zoomingIn;
    if (!isZoomed)
    {
        currentZoomedSection = null;
    }

    isZooming = false;
}```
#

Anyhow, this still has the same behavior. I couldn't see anything wrong in the Update function. I removed those lines of code, the while loop is the same

honest tangle
#

i.e. i know transform XYZ and rotation XYZ of point A and B

leaden ice
leaden ice
#

yeah yeah 😛

vestal arch
#

lol

honest tangle
leaden ice
#

what's the issue again?

#

It's snapping back after the loop?

#

That would have nothing to do with this code at all

honest tangle
#
mainCamera.transform.rotation = Quaternion.RotateTowards(mainCamera.transform.rotation, myRotation, 1.0f);```
leaden ice
#

it's some other code

honest tangle
#

yep it's snapping

#

back to the original rotation

leaden ice
#

Unrelated to the coroutine

#

some other code of yours

#

probably in Update/LateUpdate

#

or another component you have

leaden ice
honest tangle
#

i will paste the entire file, could you take a quick look? I already shared my Update method earlier

#

(pasting with a link ofc)

honest tangle
leaden ice
#

because you used RotateTowards, not Slerp

#

that would just rotate one degree

honest tangle
#

yes but thats what rotatetowards does no ?

leaden ice
#

no

#

was there even a loop?

honest tangle
#

isn't the last parameter 0 .. 1 threshold how far to rotate it ?

leaden ice
#

no

#

it's the maximum number of degrees to rotate

young yacht
#
public void AddXP(int amount)
    {
        playerData.xpAmount += amount;
        playerXPSlider.value = playerData.xpAmount;
        CheckPlayerLevelUp();
    }

    public void CheckPlayerLevelUp()
    {
        if (playerData.xpAmount >= playerXPSlider.maxValue)
        {
            levelUpManager.StartCoroutine(levelUpManager.WaitForCardsShow());

            playerData.xpAmount = (int)playerXPSlider.minValue;
            playerXPSlider.value = playerData.xpAmount;
        }
    }

how would i go about making XP carry over? lets say i got 50, max is 100, if i add 80 then i get a remain of 30, how can i have it carry that over? it sounds simple but im trying to wrap my head around it

leaden ice
#

you put 1, so 1 degree

honest tangle
#

ah, let me try your code then

#

i misunderstood it

leaden ice
young yacht
#

the slider is just for the user to see how much XP they have, focus on the playerData.xpAmount

#

when reaching 100 XP, you'll get a level up UI pop up

leaden ice
#

Wouldn't it just be:

if (playerData.xpAmount >= playerXPSlider.maxValue) {
  LevelUp();
  playerData.xpAmount -= playerXPSlider.maxValue;
}```?
young yacht
#

hm i think so!?

#

xD

leaden ice
#

although it's really weird/finicky to use your UI to do that

#

the UI should just be for presentation as you said

#

using it as the source of truth for what the level up xp amount is seems a bit... gross

young yacht
#

so maybe i should save the maxAmount somewhere

#

instead of using the slider maxValue

honest tangle
#

i tried your code, and it does rotate correctly during the while, but still snaps back after, so same issue as before

young yacht
#

sounds good!

#

thanks man

honest tangle
#
{
    // Convert screen position to world position
    Ray ray = mainCamera.ScreenPointToRay(screenPosition);
    RaycastHit hit;

    // Perform raycast to detect which object was touched
    if (Physics.Raycast(ray, out hit))
    {
        GameObject touchedObject = hit.collider.gameObject;
        string touchedSection = GetObjectSection(touchedObject);

        // If we're currently zoomed in
        if (isZoomed && currentZoomedSection != null)
        {
            // If touching the same section, do nothing (stay zoomed)
            if (touchedSection == currentZoomedSection)
            {
                Debug.Log($"Already zoomed into {currentZoomedSection} section");
                return;
            }
            // If touching a different section or non-section object, zoom out
            else
            {
                Debug.Log($"Touching different section ({touchedSection}), zooming out");
                ZoomToOriginal();
                return;
            }
        }

        // If we're not zoomed in, zoom into the touched section
        if (touchedSection != null)
        {
            ZoomToSection(touchedSection);
        }
    }
}```
#

this is called within Update, but eyeballing it, it shouldn't make the rotation snap

leaden ice
honest tangle
#

upon arriving to the final point of the zoom and rotation, nothing in here should be called, because nothing was touched

#

sure, but this function shouldn't pass the first if check. Let me debug if it actually does

leaden ice
#

debugging would be a good idea 😛

honest tangle
#

so this is what happens, upon clicking a spot and hence activating the transform and rotation, it indeed registers a click. But then, 1.5 s later ( my zoomDuration ), it arrives at the final point, and then it snaps, without HandleTouchInput being called a second time.

#

It is only called before the rotation even starts

#

to me that makes zero sense

#

nevermind i think i found the issue, another script

#

IT WOOOOOOOOOOOOOOORKS

#

note to self: always suspect Update methods - even from other scripts ;p

ocean mirage
#

hey, why do so many people on youtube recommend using scriptable objects for properties for something like health, healthregen etc.
that only works when you use the prefab just once, but why would you even then have that object as a prefab when u cant have multiple instances of it?
do i miss something?

low hinge
#

I think you missed something, "that only works when you use the prefab just once" isn't true

ocean mirage
#

why it isnt?

low hinge
#

Why would it be?

vestal arch
#

prefabs and scriptable objects aren't the same thing?

low hinge
#

You instantiate the object and the reference to the scriptable object stays there no matter how many times you instantiate it

ocean mirage
#

yes but they share the same scirptable object

naive swallow
#

Right, because if it's the same guy with the same SO defining their stats, they should be

low hinge
#

Yeah, it sounds like you think they don't if you instantiate it more than once

naive swallow
#

If you have something with different stats, you would use a different SO

#

That's the point, you'd just create a stat block for a Goblin and a stat block for a Minotaur and depending on which one you drag in it makes the object into one monster or the other

low hinge
#

Also I think you're missing that those scriptable objects should effectively be read only. i.e. you shouldn't store state in them, state should be stored elsewhere

naive swallow
#

You would never change data in an SO at runtime

#

It's basically a database

ocean mirage
#

if i create an SO with real values, and give it to an enemy prefab, then i instantiate the enemy 2 times, both share their properties like health etc right

low hinge
#

Yeah that's the point of it. It's the flyweight pattern if you wanna read more about it

vestal arch
#

well they wouldn't store like, current health if that's what you're asking - it'd be the static stats, like maxhealth

rigid island
ocean mirage
#

dont get me wrong i use them all the time for first time data

#

then i set them to my class properties and manipulate them in my real classes

naive swallow
ocean mirage
#

exactly

rigid island
#

basically you want to modify the sats you copy them then change the copy not the ones on SO

ocean mirage
#

i wanna know if i miss something since many utubers say just use scriptable objects for that case

#

and i think no, that only works if i have 4 enemies created with 4 by hand created SOs

low hinge
#

Some scriptable object architectures DO allow you to store runtime data in SOs (and then reset again), but those are specialized and even then I think some of them require separate SOs per object. Haven't worked with them much

ocean mirage
#

allright so i keep using them for like start values that i wanna scale and keep manipulate my normal class properties

rigid island
#

if you need to modify it then you could potentially make a runtime SO and then dispose of it, but that IMO is messy and better off you'd use a POCO you can copy from SO or just regular field values

low hinge
#

What's a POCO?

rigid island
#

like a regular object, class/struct

#

POCO (plain old C#/Clr object)

low hinge
#

Ah ty

ocean mirage
#

there is also that createinstance or something for SOs but then u lose the reference on that so i dont use that

low hinge
#

That gets really messy really fast

ocean mirage
#

yeah felt the same

#

thx all

hybrid marten
#

Hey I don't know where to put this but my game is using 100% gpu only in certain spots and I have no idea why, here's some profiling I just did can I have no idea how to find out anything from this

leaden ice
#

If you want to reduce that, you need a framerate limit of some kind

#

Assuming you don't have a CPU bottleneck of course

hybrid marten
#

I am using vsync, the problem is only a specific area is making the game lag and I don't know how to diagnose why

#

CPU is looking fine atm

leaden ice
#

Use the frame debugger

hybrid marten
#

I'll send a pic of it

#

I swear I just used it but I can't find it

#

Okay this is a normal frame

#

This is in the problem spot

#

I dunno what I should be looking for

steady moat
#

It can also be something else. The best would be to use a platform specific Graphics Profiler.

#

Such as PIX for Windows.

#

Otherwise you can remove things till you get to a situation where it does not lag

hybrid marten
#

There's no way to tell from this if it's like, a shader that's unoptimized or something?

tough carbon
#

I am studying [the code] (https://github.com/llamacademy/minigolf) and found out this code

            LevelPrefab = Resources.Load<VisualTreeAsset>("UILevel");

I don't get how could it work if UILevel.cs is stored into "Assets/UI/Components" folder, while Resources.Load() documentation says:

Loads the asset of the requested type stored at path in a Resources folder.

GitHub

A minigolf microgame made with Unity for educational purposes - llamacademy/minigolf

rigid island
#

resources is hella outdated btw, probably best to just link it through the inspector via filed or use addressables.

young yacht
#

its good for items, default states and such

#

if you want to change data during runtime using JSON

woven nimbus
#
Quaternion deltaRotation = shipCameraTransform.localRotation * Quaternion.Inverse(playerShipTransform.localRotation);

//ensure deltarot is the shortest path
if (Quaternion.Dot(deltaRotation, Quaternion.identity) < 0f)
{
    deltaRotation = new Quaternion(-deltaRotation.x, -deltaRotation.y, -deltaRotation.z, -deltaRotation.w);
    Debug.Log("big chungus");
}


Vector3 twistAxis = Vector3.forward;
Vector3 r = new Vector3(deltaRotation.x, deltaRotation.y, deltaRotation.z);
Quaternion swing, twist;

// singularity: rotation by 180 degree
if (r.sqrMagnitude < Mathf.Epsilon)
{
    Vector3 rotatedTwistAxis = deltaRotation * twistAxis;
    Vector3 swingAxis = Vector3.Cross(twistAxis, rotatedTwistAxis);

    if (swingAxis.sqrMagnitude < Mathf.Epsilon)
    {
        float swingAngle = Vector3.Angle(twistAxis, rotatedTwistAxis);
        swing = Quaternion.AngleAxis(swingAngle, swingAxis);
        Debug.Log("swingangle");
    }
    else
    {
        // more singularity:
        // rotation axis parallel to twist axis
        swing = Quaternion.identity; // no swing
        Debug.Log("elseswingangle");
    }

    // always twist 180 degree on singularity
    twist = Quaternion.AngleAxis(180f, twistAxis);
    //return;
}
else
{
    // meat of swing-twist decomposition
    Vector3 p = Vector3.Project(r, twistAxis);
    twist = new Quaternion(p.x, p.y, p.z, deltaRotation.w);
    //twist.w = Mathf.Sqrt(Mathf.Max(0f, 1f - twist.x * twist.x - twist.y * twist.y - twist.z * twist.z));
    twist = twist.normalized;
    swing = deltaRotation * Quaternion.Inverse(twist);
    swing = swing.normalized;
}
woven nimbus
rigid island
#

what is even going on here..

opaque vortex
#

Where is a good place to ask questions about garbage collection systems in unity. I am really having issues with a persist leak

woven nimbus
#

it starts oscillatiating, ive tried several different methods of trying to fix the issue but none seemed to work :c, ive linked the barebones code any suggestions on how to fix the sign ambiguity?

rigid island
#

just checking

woven nimbus
# rigid island what is even going on here..

https://allenchou.net/2018/05/game-math-swing-twist-interpolation-sterp/ its a sterp function, it splits the slerp movement into 2 parts a swing and twist part. Allowing u to alter the "roll" of the ship at a different speed

rigid island
#

Ohhh okay. My monkee brain only can handle eulers mb lol

woven nimbus
# rigid island are you intentionally putting quaternion values manually ?

i use this rn: Quaternion swingSterp = Quaternion.Slerp(Quaternion.identity, swingFull, 0.01f); im going to scale it based on the current speed, distance to object, etc once i get the sign ambugity issue solved. I didnt include it since i dont think the issue stems from this. (ive got one for twist as well)

safe dock
#

every time i try shooting my gun even when my cursor isnt on the pause button it always pauses the game, is there a reason?https://hastebin.com/share/sajawihike.csharp

rigid island
leaden ice
#

Don't ignore your console window and the errors therein

safe dock
safe dock
dawn nebula
#

I need to take a string and form a vector2 where both of the values range between 0 and 1. Different strings must yield different values.

#

And tips?

leaden ice
#

Like parse it?

#

E.g. parse "(6, 7)" into a vector?

dawn nebula
# leaden ice Wdym take a string

For context, I have a pattern that appears on a card. I would like to offset this pattern randomly across all cards so they don't all look the same. I have potentially hundreds of different cards. I was thinking of using either the card name or ID to form a Vector2 to offset this pattern in the shader.

#

The offset needs to always be the same.

leaden ice
#

Then generate two floats

dawn nebula
leaden ice
#
int hash = myString.GetHashCode();
Random r = new(hash);
Vector2 v = new((float)r.Next(), (float)r.Next());``|
leaden ice
#

That's what hashcode will do

dawn nebula
leaden ice
#

You could use MD5 hash or even a custom hash function too

#

That might be more stable across different platforms

dawn nebula
#

Hmm, I guess the only issue is generating a Random object every time a string is set.

leaden ice
#

You can reuse it

#

Just set the seed

#

The string itself is garbage too anyway though

#

Probably worse than the Random

dawn nebula
leaden ice
#

Correct

#

But if you're worried about that you could also use a custom PRNG

#

(random number generator)

limber fog
#

there is a hitcast attached to the bullet that is 0.5 in distance.

#

i could extend the distance of the raycast, but that might make the bullet hit to early

graceful flume
#

Hi guys, i'm trying to make a grid based game and i have a question. I found out that i can store the data of all the grid tiles in several different way using 2d array, list or a dictionary. Which way is the optimal and more performance way ?

#

My game have a fixed amount of tiles all the time so maybe a 2d array is good enough ? What if i want to make complex logic for every tiles ?

rigid island
#

also unity already has a Tilemap / Grid that can also be used and has its own optimizations

leaden ice
#

Dense grids typically benefit from a 2D array.

Sparse are better with a dictionary usually

fiery steeple
#

Guys :
Why I can't use / there's no Shuffle method on my list please ? i also tried to make it and array instead of a list but still no Shuffle method on it 🤔

rigid island
fiery steeple
vestal arch
vestal arch
round violet
#

when you update a animator var, will the animator run the various available transitions conditions to check if it can transitions ?

#

does it check if the variable changed before doing that ? im wondering if setting on each frame an animator parameter to the same value will just make the animator try to transition on each frame

vestal arch
#

generally don't worry about perf until it becomes a problem

round violet
#

well here i got 300 animators so i care lol

#

and generally knowing such things upfront is better to avoid annoying refactoring over and over again as you learn them

unkempt meadow
#

Is there such a thing as a sound event (like animation event) where a thing happens at the right point in the sound clip?

young yacht
#

you call a function that calls a sound

vestal arch
unkempt meadow
#

no, man

#

I'm looking for the reverse

young yacht
#

i dont know of any other way of doing it accurately

#

in the sense it plays on the exact frame you want

unkempt meadow
#

I'm looking to call a function when a certain point in an audio files is reached

young yacht
#

ah i see

#

dont know about that

round violet
vestal arch
#

1000 transitions, 2000 parameters checked per frame isn't gonna do much

#

but i see what your question is

round violet
#

so, does the animator run the various available transitions conditions to check if it can transitions on each parameter update ?

vestal arch
unkempt meadow
#

Why is there no audio channel here lol?

Anyway, so there's no such thing as a sound event where I would call a method based on a point in the audio clip?

I need to make the logic reverse I guess

steady bobcat
unkempt meadow
#

actually maybe I could tho

#

I think I could

#

it's just a thing like sound event would be much easier

steady bobcat
#

I see no reason why not, you can have a new component that wraps playing and can invoke its own event when you desire

unkempt meadow
#

specifically, I am working on some underwater breathing sfx

#

I have more states like more panicked breathing, slower and faster etc

#

and when I transition to a faster or slower breathing, I want to make sure that the exhale happened first for example

#

but I could make a timer and check for time elapsed

#

but that could be kinda iffy because I was leaning more towards a long, loopign breathing sfx, rather than short inhale and exhale

#

but the latter would be much easier to control, I could just wait until clip stops playing

steady bobcat
#

There are a few ways to implement it but its all doable

unkempt meadow
thin aurora
#

Alternatively you can do a bit of a nifty thing using Random if you want something that works with a list or IEnumerable:

var shuffledEnumerable = list.OrderBy(x => Random.Shared.Next());

Just make sure to do it for Unity's Random if you want that. I forgot the syntax.

steady bobcat
#

I usually just loop over the list/array once and do a random index swap to shuffle. the other method works but is linq so not ideal as its not done in place

delicate granite
#

hi,
is there a better way to do a loop that loops every time one of these subroutines finish? because for some reason the while loop just crashes unity. would a do while loop be better?

void Game()
    {
        while (playing)
        {
            if (!bStand) CheckWinner();

            if (!playersGo) EnemyTurn();
            if (playersGo) PlayerTurn();


        }
    }
vestal arch
#

a while loop like that would run all at once

#

if Game is called from Update, you already have a loop there, you would use if instead

delicate granite
#

oh okay thanks. Game is called from Start but I'll just move it all to update and remove the loop and put csharp if(playing) instead. thank you

vestal arch
#

if you want to keep the same flow, you would have to make Game a coroutine or something

#

are those 3 functions coroutines?

lyric moon
#

alright im real confused about some animator nonsense thats happening to me

#

all my characters are loaded from an assetbundle and share a base animator controller (overrides for each)

#

i have a script to drag the screen to rotate the character, which utilizes OnDrag(pointereventdata)

#

this does Transform.Rotate on a bone in the animated character

#

for most characters this works fine, however just for one character its refuses to rotate unless the animator is disabled

night harness
#

if the transform is being animated modifying the transform via code isn't gonna do anything
(transform being animated meaning if the animations target those properties in their keyframes)

lyric moon
#

thats what i thought but its been working fine somehow till now

#

somehow all other characters rotate fine

#

but this specific character wont

vestal arch
#

you sure this is a code issue?

lyric moon
#

its not the animation, ive made it use the same ones as the other characters
its not the animator, its an override

night harness
#

is the hiearchy diff?

lyric moon
#

all characters have the same hierarchy layout i believe

vestal arch
#

is Apply Root Motion set

lyric moon
#

it wasnt originially but now it is

#

the working characters have it set

#

working character

#

not working

#

exact same layout, animator is on the same object, rotating the same object, uses the same base animator controller

#

uses the same animations even right now but that still didnt work

#

ive tried everything and im completely stumped

night harness
#

(did you check if root motion was on for the broken one)

lyric moon
#

lemme check again to make sure

#

working

#

and no, it isnt culling mode

#

other working characters are also Always, infact i should change it to be Always on that one too

#

ive tried deleting and re-adding the entire animator component

#

ive removed all animations besides the test one

vestal arch
#

missing avatar?
-# i don't actually know what the avatar does

lyric moon
#

nah others have missing avatar too
and also i dont know what it does other than for humanoids

night harness
lyric moon
#

currently building a new bundle for the working character to see if its some change that happened between builds of working/not working character that caused the issue

vestal arch
#

-# i understand all these words but not in this order
-# i only work in 2d so i don't really have context for that lmao

lyric moon
#

basically you can enable/disable 'limbs' and stuff

#

for animations

#

afaik

vestal arch
#

eh i'll figure it out if i need it
anyways, does the test animation you've left control transform?

lyric moon
#

it was, but i removed any keyframes for that while troubleshooting

#

there may be some weird leftover curves or something maybe? i know that stuff is a pain

night harness
lyric moon
#

i tried moving my rotation code to LateUpdate but its a Transform.Rotate not a set rotation so that doesnt help haha

#

my animator object is still packed as an fbx while my working one isnt, maybe its related to the fbx import settings

night harness
#

could be yeah

lyric moon
#

ill try unpack and see if that helps

night harness
# lyric moon working character

generally i'd suggest doing the opposite of this in my experience in the future btw

ideally you want the transform changing via code above the animation for these kinda reasons

#

that way the animation can't control the code changes even if wanted to since it's not in the animations scope

lyric moon
#

im rotating the prefab elsewhere and dont have access to anything higher than that in my use-case

#

normally i wouldnt be rotating a bone thats part of the rig haha

lyric moon
#

and it is updating the bundle im monitoring downloads

#

its definitely some stupid animator issue

#

if i disable the animator it rotates fine

#

god its so weird

#

i just DISABLED root motion on runtime and it started working
then i reenabled and it stopped
then i re DISABLED and it still wasnt working

#

its like any update to the animator makes it work for a sec

#

until theres another update

#

i think it really must just be some weird bug
im sure if i remade the prefab from scratch itd just start working

#

yeah just retried everything

its not the animations
its not the component

#

im gonna try plug in a different animator controller entirely i guess

#

noope

#

Okay no. That didn't work either.
i made one that worked literally last night 😭 it has to be an issue with the FBX right??

vestal arch
lyric moon
#

👍

hexed scarab
#

Hi ! I'm trying to make a multiplayer online game in unity (did local co-op and first time trying online) and I want to start the game when I'm the host but for some reason everything prints false and I don't understand why.

#
 public void LoadGameScene()
    {
        Debug.Log("Is server ? " + NetworkManager.Singleton.IsServer);
        Debug.Log("Server is host ? " + NetworkManager.Singleton.ServerIsHost);
        Debug.Log("Is Host ? " + NetworkManager.Singleton.IsHost);
        Debug.Log("Is Client ? " + NetworkManager.Singleton.IsClient);
        if (NetworkManager.Singleton.IsHost)
        {       
            Debug.Log("Load level 1");
            NetworkManager.Singleton.SceneManager.LoadScene("Level1", LoadSceneMode.Single);
        }
    }
oblique spoke
hexed scarab
#

Ohhh got it

#

So I need to initialize it at Start() manually ?

#

I saw that there was a StartHost() function but I wasn't sure if I needed to call it myself

oblique spoke
#

It might be configured to auto start, but it might not have completed yet depending on when you are calling LoadGameScene.

hexed scarab
#

Well I'm just calling it on a button press so it should have been already initialized

oblique spoke
#

Auto starting settings are most likely on NetworkManager's inspector. Let's move this to #archived-networking

round violet
#

is there a small gain of time of making a job a dependency of another, (i assume there is a smaller scheduler overhead if its done once then twice using Complete()

#

in my case Job2 isnt reading data from Job1, but Job2 needs to run after Job1

brazen tartan
#

Is there any solution to snap objects perfectly together?

vagrant blade
#

Not a code question. If you hold V, you can use vertex snapping while dragging the object.

brazen tartan
#

My fault. But thank you

fiery steeple
fiery steeple
fiery steeple
vestal arch
fiery steeple
thin aurora
vestal arch
fiery steeple
thin aurora
#

Otherwise just use the OrderBy, but make sure to use Unity's Random

#

Then try OrderBy in that case

fiery steeple
#

This is the code I have, I extended the List class to have the Yale algorithm for Shuffle :

    private void GenerateMinesLocations()
    {
        minesLocations?.Clear();
        List<Tile> tilesCopy = tiles.Cast<Tile>().ToList();
        tilesCopy.Shuffle();
        int minesAmount = Random.Range(minesSpawnChances.x, minesSpawnChances.y);
        
        for (int i = 0; i < minesAmount; i++) {
            tilesCopy[i].Value = -1;
            print($"{tilesCopy[i].Coords.x}, {tilesCopy[i].Coords.y}");
        }
    }
thin aurora
#

But the Shuffle method didn't work, you said?

#

Otherwise just make your own extension method

fiery steeple
fiery steeple
thin aurora
#

Which pretty much works fine, if you want

fiery steeple
# thin aurora

I'm not familiar with LINQ enough, how's that work (meaning your code above) ? 🤔

steady bobcat
#

using the LINQ extension method to do this will require you to make a new list/array so its often not ideal

fiery steeple
thin aurora
#

You don't need to make a new list or array

#

Just iterate it and it won't allocate additional objects

fiery steeple
thin aurora
#

The only important thing to note here is that iterating it multiple times means that it will reshuffle, meaning the resulting collection will be different

thin aurora
#

This was System.Random, and it's not supported in this context

#

I forgot the syntax, so you need to add it yourself

#

Probably Random.NextInt() or just Random.Next()

fiery steeple
thin aurora
thin aurora
#

Just replace it with Random.Range(0,100)

#

Or make sure the upper part is the list's size

steady bobcat
#

😆

fiery steeple
#

I'm really confused

thin aurora
#

There are two random classes, you can blame Unity for the confusion

fiery steeple
thin aurora
#

Because once again I did not know the syntax

#

So, change it to that

fiery steeple
#

Like so ?

thin aurora
#

Just range it between 0 and a high number

fiery steeple
thin aurora
#

It's clear you are inexperienced in general and so my suggestion of a simple one liner definitely doesn't fit your use case, so I suggest you just use a proper shuffle method

steady bobcat
#

otherwise its an IEnumerable<>

fiery steeple
thin aurora
#

Probably better to keep a separate array/list available in which you can buffer the ordered variant of the collection so you can put the result in there

steady bobcat
#

you need to do tiles.Cast<Tile>().OrderBy().ToList()

#

this code is a fuckin mess

thin aurora
#

I regret suggesting this

steady bobcat
#

⚠️ ToList() will allocate a new list when used so not good to use very frequently on a large collection
Ideally you randomise the collection ONCE or pick a random index instead if that is enough for the use case

fiery steeple
thin aurora
#

The whole point was that they iterate it and use the result, and possibly reshuffle next iteration. Regardless for this to be anything proper you should keep a separate buffer to put the result into. You don't need to allocate a list/array when you do this properly

fiery steeple
leaden ice
#

there are better/faster ways to randomize a list/array that don't involve LINQ anyway

thin aurora
#

Because it needs a comparer

#

Well yes, that's why i regret it

thin aurora
#

The whole point was because they didn't want an extension method or w/e but this really just complicates it

fiery steeple
leaden ice
fiery steeple
steady bobcat
#
for(int i = 0; i < list.Count; i++)
{
    var item = list[i];
    int randomIndex = Random.Range(0, list.Count);
    list[i] = list[randomIndex];
    list[randomIndex] = item;
}

shuffling a list ourselves

#

its not a crazy concept, swap shit in a random way so things are different

vestal arch
steady bobcat
#

i just used what they already did in what i could see 🤷‍♂️

thin aurora
#

Depending on the type it's either Count, Count() or Length

#

Just pick what PraetorBlue linked

#

If you don't want it to shuffle your existing list, you need a buffer list and use Array.Copy or another copy method to move them over to the buffer

fiery steeple
leaden ice
#

tiles

#

you can always just make a copied list with:

List<Tile> tilesCopy = new(tiles);```
fiery steeple
#

rather a 2d array

thin aurora
#

Regardless PraetorBlue already posted a much better solution for shuffling which will work infinitely better anyway

leaden ice
# fiery steeple

the list constructor (my code sample) should handle that fine assuming the goal here is just to have a shuffled list to pull random tiles from

fiery steeple
#

Then where I do all the rest with the Casting and stuff ?

leaden ice
#

you don't?

#
List<Tile> tilesCopy = new(tiles);
tileCopy.Shuffle();```
fiery steeple
#

That's what I have in my extension method... so back to square 1 👀

leaden ice
#

yeah what's the issue with it?

fiery steeple
#

Nothing but wanted to know if there's an already existing stuff to do that directly instead of writing that code

leaden ice
#

no

#

this is the best/fastest way

fiery steeple
#

it complains

steady bobcat
#

you may have to make the list yourself from the 2d array

fiery steeple
#

yeah so back to square 1

steady bobcat
#

A normal array ofc avoids this

#

no not that way 🤦‍♂️

thin aurora
#

I don't understand why you don't just use the shuffle method suggested three times

#

You literally have an array of a fixed size. Everything you do now is excessive because of extra allocation, not to mention it won't work as well

leaden ice
#

Do they mean to shuffle the existing array in place?

fiery steeple
leaden ice
#

What's the end goal here

leaden ice
#

You could totally rewrite the shuffle algo to work with the 2D array

thin aurora
#

You can just call the shuffle method twice

leaden ice
#

Just with a tiny bit of math

thin aurora
#

Or whatever amount you need it

thin aurora
fiery steeple
#

I need to retrieve X elements from that list to creates mines in my Grid (It's MineSweeper)

leaden ice
thin aurora
#

Well yes, I suppose it needs a bit more work

#

Maybe you do that, but then switch direction or something?

#

I can't imagine this doesn't exist already

thin aurora
leaden ice
#

You just change the array accesses to use / and % to get the x/y from the single index

thin aurora
#

Same approach, but for 2d arrays

leaden ice
#

Yep

thin aurora
#

No, this is a flattened approach to insert values into a 2d array it seems

#

No shuffling is done

fiery steeple
#

my brain is melting 🤣

vestal arch
#

you asked about a random element there so i answered about a random element

thin aurora
#

Which, by the way, would work in this case if you were to use a random index. But it doesn't guarantee you quickly insert an array with all values since the index is completely random

fiery steeple
vestal arch
#

either just randomizing a lot or doing linq with lazy evaluation would probably be better
you don't need to shuffle 100 cells if you only need 16 to set as mines, do you

fiery steeple
#

no wait

#

I need to do the shuffle of 100 before drawing 16 mines, otherwise a part of the pool will never be part of the ones drawn

vestal arch
#

in the method without shuffling, you'd be randomizing across the entire board

vestal arch
#

ok let's think about the base case, just doing 1 mine out of a 10x10 board

#

there's 2 approaches - shuffle and take the first cell, or pick a random cell
these have the same random outcome

fiery steeple
#

I shuffle and take X first cells

vestal arch
#

now if you want 2 mines, you could shuffle and pick the first 2, or you could pick 2 random cells by index (with a repeated drawing if you happen to draw the first cell again)

fiery steeple
#

that's what I have in mind

vestal arch
fiery steeple
vestal arch
#

you can just loop until you find one that's not a duplicate

fiery steeple
vestal arch
#

of course there's a statistical chance that it'll be a duplicate forever, but with the finite space of prng, it's not gonna actually be an issue

vestal arch
fiery steeple
vestal arch
#

because you only need a small random selection

#

to be clear im not saying the second approach doesn't potentially waste resources

fiery steeple
#

So you shuffle only the X first elements ?

vestal arch
#

that would just get the first X elements but shuffled, rather than getting X random elements

fiery steeple
#

Yeah that's why I'm confused by your question 😄 If I don't shuffle the entire board, I will never get elements > than X

vestal arch
#

i specified "lazy evaluation" - that might help, depending on how stuff is implemented. im not sure, ill have to look into that

#

my point is - there is no "perfect" solution here that doesn't "waste" resources in some way or another

vestal arch
#

i might be phrasing some stuff confusingly. give me a sec to get on pc to check some stuff

fiery steeple
#

Let me pseudo code it for you maybe to understand my POV and why it's the best solution :

  • Have a list of Y elements not shuffled (Let's say we have 100 elements, so Y = 100) where each element has a value corresponding to its index (1,2,3,4,5,...100).
  • Make a copy of that list and save it in a new List variable called listCopy for instance (to preserve the original list).
  • I need a random value between MIN_VALUE (let's say 10) and MAX_VALUE (let's say 25) determining the amount of mines that will be present in my grid. Let's say the random gives us 20.
  • Shuffle the wholelistCopy list and get the first X (20) from it. Now the values could look like something like this (78,14,5,9,43,...). So you can see that I can get numbers higher than 20 and is more performant than doing a for loop < X (20) and Get a random number from the list until it's not a duplicate. We could make it better by removing each element we already drawn but there's still the issue of Shuffling on every iteration of the loop instead of my first approach where we shuffle only once (in the beginning).

So this was my thinking on why this is the best approach.

#

I hope it makes more sense 😄

vestal arch
#

you would not shuffle on every iteration of the loop

#

shuffling is already an iteration

fiery steeple
#

oh yeah my bad but you will still need to get a random value between 0 and the list.Count

vestal arch
#

yeah shuffle does that too?

fiery steeple
#

Nope, I explained badly

#

but you need to call Random.NextInt() on each iteration

vestal arch
#

which shuffle already did (in your proposed case)

fiery steeple
#

while in my case I don't even need that making it save resources as I get the X first elements of the shuffled list

fiery steeple
vestal arch
#

im so confused why you're actually against that approach

#

i think you're not realizing that there's still quite a lot of work done behind the scenes?

fiery steeple
#

Because of the random numer that needs to be generated on every iteration

#

and also because you could find yourself on duplicates making you have to redraw again

vestal arch
#

shuffling would get more random numbers

vestal arch
fiery steeple
#

Oh

#

I don't know the innerworking of the Shuffle so yeah you could be right on this

vestal arch
#

they both have drawbacks, so which one is "better" is really subjective

#

for an n-size array and k random elements
shuffling (without lazy evaluation) does n allocations, n-1 random calls+swaps
shuffling (with lazy evaluation, but probably not realistic) would do k allocations with n-1 random calls+swaps
direct random would do minimum k random calls, and potentially more.

i do have a new idea, which would be manual shuffling up to k, does n allocations and k-1 random calls+swaps

fiery steeple
#

That's why I complain about Unity not having a solution for this kind of things already implemented for us to use directly

vestal arch
#

it's such a specific thing

chilly surge
#

If you just need to randomly pick out a subset of items from a pool, you don't need to shuffle the whole pool.

vestal arch
fiery steeple
chilly surge
#

If the pool is allowed to be mutated, you can definitely do it with no allocation and just k swaps, no need for n at all.

#

Simply do a Fisher Yates and stop early at k.

vestal arch
#

maybe linq Shuffle will be lazy

fiery steeple
#

Is it possible in Minesweeper to have this many mines (-1) in a row (at line 2) ? 😄

chilly surge
#

Oh so the question is actually about picking random indexes to initialize a mine sweeper game.