#archived-code-general
1 messages · Page 453 of 1
lol
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"?
I wanted a runtime node graph library, I found one as a starting point but comes with a minimal starting set of options/nodes
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
I thought about placing round UI buttons (I need interactable graph nodes), but I am not sure is this the best way
<@&502884371011731486> either scam or advertisement, your pick
last i heard the update would be a totally new replacement and the current API will be mothballed, but it's been a while since i checked on that
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.
The way you described doesn't work but what you're looking for is a singleton
google Unity Singleton
you will find real working examples of how to do it
Would a Singleton be bad for a single player health system? Everywhere I look says yes.
well, depends on what you mean by "bad"
I feel like other classes being able to access the health without a direct reference would be good.
i don't think it'd be bad in itself 
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
I have a player class that acts as the core of the player, so I could do that instead.
I think depending on how your game works it's pretty rare to have a situation where you need your player to gain or lose health when you wouldn't incidentally already have a reference to the player object.
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.
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
There are many ways ranging from very complex to very simple depending on how complicated your items can get
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
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
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
yeah that's fair
I'm gonna go... consider how to do it (before implementation so I don't screw myself), thanks!!
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());
}
}
}
First place to look is your while loops
you have that if (tries > 10) break; but you never actually increment tries
Ah. Forgot to shift that over from the more extensive script that I dumbed this down from.
a safer formulation would be a for loop. for (int tries = 0; tries < 10; tries++)
Probably could just use another forloop
then let the !Utilities.IsNullOrEmpty(Colliders) condition be the early out
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
new Quaternion() < this also does not produce a valid Quaternion (unfortunately). You need Quaternion.identity
It's used in the code that this came from. Testing it out in a simpler environment.
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.
Probably stencils. Looks like stencils so shader related
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
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
How helpful is the Unity Learn Junior Programmer course?
very helpful if you're a beginner who knows nothing about Unity
not that helpful if you're not.
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.
it's helpful to understand how your code interacts with the game engine
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:
- Use abstract Monobehaviour classes.
- Expose a Monobehaviour field, cast to the interface in Awake and store it in some other field.
Which is more standard?
Abstract classes is more common. The second is sometimes done, usually along with a custom attribute and property drawer to constrain the type in the inspector.
- Use a separate distinct component that all those objects have, and use a direct reference to that type.
I prefer 3.
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
It's something you heap into one big game data structure. But that thing might be a uuid for a completed quest, for example
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.
So the architecture I would be going for is to have one big structure that has a bunch of lesser structures like party information, character information, and map information?
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
Ah, so that's just unavoidable then
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.
Let's say I have multiple save files and I don't want to read every single one in their entirety. Just a specially designated header section with enough information to describe the state of that game (Things like location, time played, gold, etc). Is there a way to do that? Or do I have to read each of those files in their entirety to get that information?
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 ?
This question is too broad to provide any decent answer.
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
TotalincomeperInterval is a class variable? Do you use it elsewhere?
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 😦
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
CC wouldn't work for something like that. At least not without extra code.
If the character is a dynamic rb, on the other hand, it should work out of the box.
Yeah, it will work with RB, but CC has a realy handy StepOffset. There are ways of doing something similar to it with RB player, but as I know they are not really effective, precise and smooth
This is a very weird behavior.
Can you try commenting out all of the code related to rotation and see if the issue happens?
A CC is just a collider with some hardcoded logic. Anything you can do with it, you can also implement with an RB.
try to freeze Y rotation, so colliders will not be able to rotate your RB, only your code
Are you sure? As I know, StepOffset is computed somewhere deep within the engine and you can not access such code
there is one which is this
Obviously, you can't - it's a feature implemented in the CC. But you can implement your own.
@deep stirrup
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
Yes of course there's a way to do that. If you can imagine a thing you can write code to do it.
Do you have any code in OnCollisionEnter in any of the scripts?
@deep stirrup do you mean that this will work even with the y-rotation freeze?
not currently. but I will
Of course, I mean that it uses some features and functions that are not accessible without source code. I tried to research this, but I found only simple methods using raycast, which can be really buggy
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.
I think? As I know, freeze rotation and position affect only physical computations, not code, so it should work
This is likely how it is implemented under the hood. There's no special magic behind it.
there is no extra colliders. it is related to angular damping I guess. the default value was 0.05 and it was rotating infinitly. but when I increased it the rotation got weaker
okay, I will try to research it further, thank you for consultation!
I will try. thanks
I see. Then I guess what Яitbulau mentioned is the way.
it worked. Thanks again 
You might be able to implement it with CC, if it can receive OnCollisionEnter messages. This might be true if a dynamic rb is colliding with it.
Then you just need to apply the relative velocity to the next CC movement that you apply.
Okay, I will try👍
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?
What is?
So how might I do that then?
easier way might be to have a 2nd file for meta-data paired with each large "main" file. That way you can still use simple formats & serializers like json.NET and avoid a custom reader.
If you know the size of this block you can just read that via file stream: https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.read?view=net-9.0#system-io-filestream-read(system-byte()-system-int32-system-int32)
Kinda like how Unity already does things then? So I'm guessing that I would include a contingency that, if the metafile is missing, it reads the file proper and creates a new one? Something like that?
probably a good idea to have a self-healing feature in a situation where someone could just delete that fire or otherwise destroy the (unmanaged) association of the two files.
FWIW if you are using json.NET you can parse the json text to create an abstract syntax three of the file and then navigate that syntax tree to the data you actually want to deserialize. however that still requires a full file read and parsing... only worth it if your bottleneck is in the actual deserialization.
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
well try debugging - check if the null check is passing, check the value, etc
you should really share the full script(s) here. You shared some out of context snippets that make it hard to follow what we're actually looking a.
alr. its in a messy state which i'll clean up but i'll grab all of them real quick
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
yeah i think i got confused there
You should also log additional stuff like:
- how many cards are in the
cardslist/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;
}```
stupid question, cards is an array, for me, Count does not come up as an option. how do I go about doing this?
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
Turn off Collapse
Toggle this off
but it seems like probably all the cards have a value of 0
why is it only printing "Card w/0 value" one time
they're not supposed to
this card is presumably not in your array
yeah the one card
yeah
so - you're going to get an error
i clicked hit once
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
ok I didn't know you had this if (card != null) bit
sorry i was supposed to say
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
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?
yes
Start runs much later
Awake runs by the time Instantiate returns
you didn't show the code before that was setting the value
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();
}
}
yeah - if that was Start before it would not have run by the time you were calling CountCards if it was just instantiated then
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
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?
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
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
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.
That's interesting. How do you go about handling scenarios where you need to keep track of a number of game objects? Like when you want to find the closest enemy for some purpose
some component handles this and this information is either given to the others that need it or they have a ref to this component instance
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.
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
I haven't seen the full talk or looked at it in awhile so I'm not really sure what the comparison here is, like what this modular design is compared to a singleton. A singleton referencing other singletons referencing more singletons sounds like a made up problem
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
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)
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
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
is your camera movement in lateupdate?
Usually for large systems, like an ability system where every character can do unique things, you'd want to plan this out carefully. The real issues come when you want to create more functionality on top of your system.
Stuff like your UI manager being a singleton, or a door using a unityevent won't ever matter
does your rb have interpolation
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
it means your code is breaking the RB interpolation
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
rb.transform.localRotation = Quaternion.Euler(0, MouseHorizontalInput, 0);
like this
That's modifying the Transform directly
that will break interpolation
geez, so what would i need to do add torqe to make the characters rb turn?
no
just rotate the RB
rb.rotation *= Quaternion.Euler(0, MouseHorizontalInput, 0);```
sweet, great call i appreciate it
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?
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?
Is it normal for Unity to lag whenever I load a new scene for the first time?
Usually it won't allow you to have two of the same components on a script? Either way you should be able to just drag the component name into the relevant box
Like you should be able to drag the component itself instead of the game object
Open the object you want to drag into in a separate properties window
By right click on it and select properties
Then you can directly drag the components
Ah I see. Hmmm, is it bad practice to do this? Feels like bad practice.
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?
Storing the “whole real object”as opposed to what?
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
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
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
seems like your inventory is not very OOP if you are reaching into it by index
why not?
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
Personally I would not do instanced scriptable objects for items. Definitely use them as data objects, but I like using them mostly as configs. Something to be given to other classes or mono behaviours for set up.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
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
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
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
fr thanks
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
anyone decent at using quaternions for main camera rotations ?
Very few people are. Thankfully everything can be done with the helper functions so you don't need to be
What exactly are you trying to do? "using" quaternions is very easy once you understand it, of course you wouldn't modify them componentwise, but use the helper functions as Nitku said and multiply the quaternions (apply rotations) together appropriately
Then you're not setting it all as ignore. Use the UITK debugger and take a look.
Also #🧰┃ui-toolkit
i have a main camera looking top down that i simply want to rotate 90 degrees over a 1.5 s duration and then for it to stay in that rotation afterwards
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
Would need to see the code to help further on that
not at home rn but can send u after
please do
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I've been using Claude to help me out i understand the general concepts
if big scene yea
real object?
isnt this an interface?
each item inventory could have a IUsable interface
you call it and do whatever with it
such as Use()
Hi there its my first time chatting and I could really use some help 🙏
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
last bullet point, being the important one to ask
u can use external paste bins for long !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
A tool for sharing your source code with the world!
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...
heres the vid im using as reference as well
whats the exact issue? u cant get a raycast to detect em?
what's your "grid" made out of?
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
it is a tilemap
Your tilemap has a 3D collider on it?
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?
It seems like you're maybe trying to copy the tutorial but you're not actually copying the tutorial? This is a very simply error where you're trying to use a variable you never declared
No cause im developing this for vr (excuse the variables i ripped them from the video i was watching sorry)
i was copy and pasting yea but trying to modify it before moving on
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.
just a tip its .forward now i believe.. transform.forward local space Vector3.forward global space
but yea.. i think u need some more basics.. and/or to move over to beginner-code
transform.forward is a world space vector
Vector3.forward is... basically unspecified. It depends which context you use it in.
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 👀
yea good call 😭 😂
all good... that's where i normally hang out and i been learning for 3-4 years now
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
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
I have to ask why isGamePaused nullable but thats a good solution changing the sim mode to "pause" it
it's a scriptable object acting as a bool variable
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
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
Does anyone have any FPS movement code?
I dont really care as long as it has jumping, walking, and sprinting
We don’t do that here
the internet has plenty
also to double back, it's a generic system I made, I can do it for floats, ints, vectors and even colours
does anyone have a simple shared memory IPC guide?
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 🤔
It's default is false, it can't be null unless it's a nullable bool (bool?)
thanks 👍
I've looked into it. What are you doing?
im using different plugins on Win and Android
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
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.
did you enable your input action asset
I'd try using Started over performed, otherwise probably some setting in the action properties there
Looks fine from what you're showing. Maybe show more code?
Also any errors?
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().
has anyone had the problem where handles work once after recompiling in runtime, then dont work in runtime afterwards?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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 ?
You sure you've not hit a breakpoint?
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
Thanks 👍
I have another question :
Is there a premade method in C# / Unity to turn a 2D array into an array (1D) please ?
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)
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
why do you have to make it a 1d array?
rather a List than a 1D array because it's easier to pick randomly from that than a 2d array
.ToArray()[i] or .Find() but I need to read more about those
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
it's just easier to do the job once instead of twice
I don't understand what you mean with the second part 🤔
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];
What the heck is the wizardry on the second one 😮
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
you're crazy 😄
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
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)
highest I've worked with is 3D, any higher its more of a pure maths thing, but very cool for induction proofs
i spent way too long figuring that out
I'm studing some of this right now but I suck at it
make it a child and set the localPosition?
I would prefer not to do that since I'm trying to find the location relative to an object as a variable instead of creating another object
like a math equation that you can pass such that you get the offset location
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
I'm wondering if adding the positions together will break when I change the angle/orientation of the reference vector
bc that broke and didn't work for me
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
TransformPoint(transform.localposition + offset)?
reference.TransformPoint(transform.localPosition)
doesn't seem to work
wait
var castCameraLocation = playerCamera.transform.position;
var castCenter = playerCamera.transform.TransformPoint(castCenterOffset);```
like this?
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)
well, what effect do you want to achieve?
just an offset on the castCameraLocation expressed as the variable castCenter
considering both position and rotation?
yes, I want to keep the origin and rotation of the castCameraLocation but apply a local transform relative to it
that's not what im asking
should the offset take into consideration the position and rotation of playerCamera
yes, so the offset is always the same relative to the root playerCamera
lemme run debug rq
it's working now, thanks
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?
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}"
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"
!logs
didnt found anything in the editor logs
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
these errors only pops up when i do Build And Run, not Build
perhaps #archived-shaders? this channel is more for c# scripting
Oh my bad!
i mean that is shader code right
yeah
i don't know shaders at all so im not too confident in identifying that lmao
ill delete my message as to not clutter the channel 
This kind of question would go to #💻┃code-beginner
And if you don't k ow how to add a script, perhaps start with doing the basic pathways on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'm not sure what you mean by that. Maybe you should provide the whole context in your original question.
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
This is really not enough context. You'll need to provide a better explanation
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
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?
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
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?
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.
like vertical scroll
A scroll view with a text component laid out nicely could work.
perfect thank you 🙂
Is that enough, the ui not following the sibling index or reorder because I don't know how in runtime
Did you look at the API docs? Specifically the transform page. Transform component controls the object position in the hierarchy in unity.
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
OverlapSphereCommand may be useful to perform these async. I am unsure if they can be used in burst jobs:
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/OverlapSphereCommand.html
Did you limit the check to certain layers to reduce the colliders checked?
im already using that
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
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
i first went for ECS but didnt had time to learn it for my deadline
Are you forcing the job to complete instantly after scheduling it or are you letting the game do other stuff in between?
You can improve performance of updating the transforms by using IJobParallelForTransform. But even better if you can avoid using transforms and game objects and render the bullets yourself.
Then cheat and split processing over different frames. Its what vampire survivors does (e.g. check xp overlaps every 4th frame only)
im just using the default Complete(), its very fast so ...
wait are you making the main thread wait for its compleation?
less than 1ms
That's way less than 1ms 😁
what is InitialUpdate() doing then?
Oh i looked at the wrong number
i guess i can try IJobParallelForTransform or rendering the bullet on GPU (got no idea how to do so, my bullets is a prefab with a few meshs)
but can IJobParallelForTransform be faster than 0.001ms ?
You should identify what is contributing most and optimize that first.
(thats how much time it takes to update a bullet transform)
I would expect it to be faster than 2.38 ms for 1938 instances, yes.
transform changes require children to be made "dirty" too, how is this bullet set up?
Make sure the bullets are not under a shared parent object. Transforms update faster when they are in the root, especially for IJobParallelForTransform
loop bullets, check if out of authorized area, add an entry in the command buffer then move transform
share code
lots of funcs, wait
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Lets us look for other perf issues then if we can see it
i guess ill test that, they were in a parent GO for better editor utility
A tool for sharing your source code with the world!
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
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
not much improvements
0.5-1.5ms
The total processing time went down by 0.5-1.5 ms? Or it is now 0.5-1.5 ms?
went down to 9ms instead of 9.5ms
can i use something like Allocator.Persistent or something ?
instead of TempJob
Yea, if they won't need to change size you can re use the same ones
i can create i once on first loop, clear on disabled
but i cannot resize it ?
No so it would help best if you have an upper limit you enforce
maybe if i set it to 3k entries or something (this will never be reached) it may be faster ? idk
Make some super big one just to test
ill test this tmrw thanks
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
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
there is a Quaternion.Slerp, isn't there
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?
yep
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?
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
do you have other code e.g. in Update that is setting hte camera rotation, perhaps with an if (!isZooming) around it?
because that other code is probably taking back over again once isZooming becomes false
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
you're saying isZoomed and isZooming aren't similar?
well anyways, I just did this again. Commented out the 4 lines of code and it has the same behavior
it is a bit of a clusterfuck i would not had written the same way myself that's for sure
{
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
so let's say i wanna do this. I know what is point A, initial point, and how point B should be
i.e. i know transform XYZ and rotation XYZ of point A and B
Quaternion start = transform.rotation;
Quaternion end = /* Whatever you want */
float elapsedTime = 0;
while (elapsedTime < duration) {
elapsedTime += Time.deltaTime;
float t = elapsedTime / duration;
Quaternion rot = Quaternion.Slerp(start, end, t);
transform.rotation = rot;
yield return null;
}```
<freezes>
yeah yeah 😛
lol
assuming transform.rotation is basically mainCamera.transform.rotation here, I still have the exact same issue with this code :
what's the issue again?
It's snapping back after the loop?
That would have nothing to do with this code at all
mainCamera.transform.rotation = Quaternion.RotateTowards(mainCamera.transform.rotation, myRotation, 1.0f);```
it's some other code
Unrelated to the coroutine
some other code of yours
probably in Update/LateUpdate
or another component you have
this isn't similar to what I shared
i will paste the entire file, could you take a quick look? I already shared my Update method earlier
(pasting with a link ofc)
i know but it should do the same thing in practice, or rather, my version should just snap to the rotation (90, 90, 90) at the end if i understand correctly
no
because you used RotateTowards, not Slerp
that would just rotate one degree
yes but thats what rotatetowards does no ?
isn't the last parameter 0 .. 1 threshold how far to rotate it ?
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
you put 1, so 1 degree
carry what over to where? Can you be specific about what all these variables mean? Why is there a slider? We need more context.
yea my bad
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
Wouldn't it just be:
if (playerData.xpAmount >= playerXPSlider.maxValue) {
LevelUp();
playerData.xpAmount -= playerXPSlider.maxValue;
}```?
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
i tried your code, and it does rotate correctly during the while, but still snaps back after, so same issue as before
this is my Update, i can't understand what would make it snap here
{
// 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
ZoomToOriginal();
ZoomToSection(touchedSection);
don't both of these functions rotate the camera?
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
debugging would be a good idea 😛
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
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?
I think you missed something, "that only works when you use the prefab just once" isn't true
why it isnt?
Why would it be?
prefabs and scriptable objects aren't the same thing?
You instantiate the object and the reference to the scriptable object stays there no matter how many times you instantiate it
yes but they share the same scirptable object
Right, because if it's the same guy with the same SO defining their stats, they should be
Yeah, it sounds like you think they don't if you instantiate it more than once
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
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
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
Yeah that's the point of it. It's the flyweight pattern if you wanna read more about it
well they wouldn't store like, current health if that's what you're asking - it'd be the static stats, like maxhealth
yes you can think of them as Static values
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
Yes, because every Goblin should have 10 hit points or whatever.
But when you hit a goblin for 3 damage, you aren't subtracting it from the SO, the SO just defines what things the goblin starts with
exactly
basically you want to modify the sats you copy them then change the copy not the ones on SO
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
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
allright so i keep using them for like start values that i wanna scale and keep manipulate my normal class properties
" use scriptable objects for that case" which case is that
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
What's a POCO?
Ah ty
there is also that createinstance or something for SOs but then u lose the reference on that so i dont use that
That gets really messy really fast
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
Unless you are using vSync or otherwise limiting your framerate, 100% GPU is the expected norm. Your computer is going to push out as many frames as it possibly can up to 100% of your hardware.
If you want to reduce that, you need a framerate limit of some kind
Assuming you don't have a CPU bottleneck of course
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
Use the frame debugger
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
At individual calls.
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
There's no way to tell from this if it's like, a shader that's unoptimized or something?
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.
A minigolf microgame made with Unity for educational purposes - llamacademy/minigolf
correct you have to have UILevel as VisualTreeAsset in Assets/Resources folder
resources is hella outdated btw, probably best to just link it through the inspector via filed or use addressables.
SO is ALWAYS static
its good for items, default states and such
if you want to change data during runtime using JSON
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;
}
im having some weird issue where when the ship is more than 90 degrees in pitch/yaw or 90degrees in roll from the origin the sign of the quaternion or axis gets inverted i think
what is even going on here..
Where is a good place to ask questions about garbage collection systems in unity. I am really having issues with a persist leak
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?
are you intentionally putting quaternion values manually ?
just checking
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
[latexpage] This post is part of my Game Math Series. Source files are on GitHub. Shortcut to sterp implementation. Shortcut to code used to generate animations in this post. An Alternative to Slerp Slerp, spherical linear interpolation, is an operation that interpolates from one orientation to another, using a rotational axis paired with the sm...
Ohhh okay. My monkee brain only can handle eulers mb lol
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)
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you probably have an error and its pausing the game
Yep you've got error pause turned on
Don't ignore your console window and the errors therein
i guess i was so tired i forgot to check... (i need a break)
thanks
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?
Wdym take a string
Like parse it?
E.g. parse "(6, 7)" into a vector?
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.
You could just do GetHashCode on the string and use that in a Random constructor
Then generate two floats
Well I need to make sure a specific card always generates the same offset. If "Fireball" is supposed to have an offset of 0.2, 0.8, then this should be consistent.
int hash = myString.GetHashCode();
Random r = new(hash);
Vector2 v = new((float)r.Next(), (float)r.Next());``|
Yeah of course
That's what hashcode will do
Oh I see.
You could use MD5 hash or even a custom hash function too
That might be more stable across different platforms
Hmm, I guess the only issue is generating a Random object every time a string is set.
You can reuse it
Just set the seed
The string itself is garbage too anyway though
Probably worse than the Random
Assuming I always provide the same seed, there's no platform oddity with System.Random, ya?
Correct
But if you're worried about that you could also use a custom PRNG
(random number generator)
ok, the hitcast is not fast enough for my needs, any other suggestions
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
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 ?
depends, storing different types of info can be split into multiple collections
also unity already has a Tilemap / Grid that can also be used and has its own optimizations
It depends if the data is dense or sparse
Dense grids typically benefit from a 2D array.
Sparse are better with a dictionary usually
Someone gave me an easier solution 👇 There's an even better solution in C#12 using the "spread" operator but Unity uses C#9 😬
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 🤔
make an extention method that uses yates
I don't know what that means 😬
interesting, didn't know a multidimensional array would implement IEnumerable, just not IEnumerable<T>.
this seems a bit more fragile than necessary though? you have well-defined types but you're hopping out of those types and back in?
IEnumerable.Shuffle in linq is for .net 10
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
generally don't worry about perf until it becomes a problem
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
Is there such a thing as a sound event (like animation event) where a thing happens at the right point in the sound clip?
animation event
you call a function that calls a sound
how many out transitions per state in your animator?
i dont know of any other way of doing it accurately
in the sense it plays on the exact frame you want
I'm looking to call a function when a certain point in an audio files is reached
not much, but here idc if its micro optimization or not, im just asking how the animator behaves
1000 transitions, 2000 parameters checked per frame isn't gonna do much
but i see what your question is
so, does the animator run the various available transitions conditions to check if it can transitions on each parameter update ?
perhaps try asking #🏃┃animation about that, definitely not a code thing
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
you can do that yourself easily with a coroutine/async function that waits the correct time (or checks until the clip is past the point you desire)
yea I know but there are things I couldn't do with that
actually maybe I could tho
I think I could
it's just a thing like sound event would be much easier
I see no reason why not, you can have a new component that wraps playing and can invoke its own event when you desire
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
There are a few ways to implement it but its all doable
#🔊┃audio ?
oh I'm stupid
Late to the party but Random.Shuffle exists (not part of the Unity Random class though so do note you need the other Random class)
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.
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
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();
}
}
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
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
if you want to keep the same flow, you would have to make Game a coroutine or something
are those 3 functions coroutines?
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
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)
thats what i thought but its been working fine somehow till now
somehow all other characters rotate fine
but this specific character wont
you sure this is a code issue?
its not the animation, ive made it use the same ones as the other characters
its not the animator, its an override
is the hiearchy diff?
all characters have the same hierarchy layout i believe
is Apply Root Motion set
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
(did you check if root motion was on for the broken one)
lemme check again to make sure
working
not
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
missing avatar?
-# i don't actually know what the avatar does
nah others have missing avatar too
and also i dont know what it does other than for humanoids
avatar can be used to whitelist/blacklist regions of the rigged body eg. you could disable changes to the legs without needing to change the clip itself
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
-# 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
eh i'll figure it out if i need it
anyways, does the test animation you've left control transform?
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
Nope, still works a-okay.
imagine you have an animationclip for holding something with two hands and an animation clip where your sprinting
you could use avatar masks so if your holding something the animation layer w/ a mask can override just the arms of the body in order to play the holding animation while everything else is still doing the running stuff
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
could be yeah
ill try unpack and see if that helps
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
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
nope still nothing UGH
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??
maybe? idrk - but if you think so you could try asking in #🔀┃art-asset-workflow or #🏃┃animation
👍
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);
}
}
You are probably checking these before NetworkManager has initialized. You generally want to wait for some sort of callback from the networking framework or check its state before trying to interact with it like this.
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
It might be configured to auto start, but it might not have completed yet depending on when you are calling LoadGameScene.
Well I'm just calling it on a button press so it should have been already initialized
Auto starting settings are most likely on NetworkManager's inspector. Let's move this to #archived-networking
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
Got it
I would ask this in #1062393052863414313
Is there any solution to snap objects perfectly together?
Not a code question. If you hold V, you can use vertex snapping while dragging the object.
My fault. But thank you
I don't know what you mean by you second line 😄
So not available in Unity ?
But what class is that because there are multiple Random from different classes
imagine you change the type of the array, now this part breaks silently without telling you
how ? Like right now I made into a List<Tile> instead of an array as the original one was a List<Tile>
This would be System.Random, Unity's Random does not have this AFAIK.
i mean the elements of the array
Tried that, it doesn't have Shuffle() either
Otherwise just use the OrderBy, but make sure to use Unity's Random
Then try OrderBy in that case
I don't get it, why would it be broken ?
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}");
}
}
But the Shuffle method didn't work, you said?
Otherwise just make your own extension method
At first no because it didn't exist on List<> nor an Arrays nor in the Random class, so when I extended the List<> class, I implemented myself which is what I wanted to avoid from the start
OrderBy has a random ordering ?
No, I wrote a little line of code using OrderBy to simulate shuffling
Which pretty much works fine, if you want
I'm not familiar with LINQ enough, how's that work (meaning your code above) ? 🤔
using the LINQ extension method to do this will require you to make a new list/array so its often not ideal
That's what I need as I don't want to Shuffle the original one
You don't need to make a new list or array
Just iterate it and it won't allocate additional objects
Doesn't work 🤷♂️
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
Like I said you need to use Unity's Random properly
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()
It says "UnityEngine" though 🤔
It essentiatelly orders by a given entry. Normally it would be a list item, but here it would be a random index. Regardless the result means you shuffled the collection based on a random set of numbers.
Yes, but Unity does not use a shared instance unlike System.Random
Just replace it with Random.Range(0,100)
Or make sure the upper part is the list's size
😆
I'm really confused
There are two random classes, you can blame Unity for the confusion
This doesn't exist either 🤷♂️
Because once again I did not know the syntax
But I looked it up, it's Random.Range()
So, change it to that
Just range it between 0 and a high number
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
you need to do var newList = tiles.OrderBy().ToList(); to fully quality it into a new list
otherwise its an IEnumerable<>
Without the copy variable it complains
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
I regret suggesting this
⚠️ 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
It complains about OrderBy()
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
there are better/faster ways to randomize a list/array that don't involve LINQ anyway
Tell me more please 👀
The whole point was because they didn't want an extension method or w/e but this really just complicates it
it complains with it too 👀
So, recently I was writing some code, and I was presented with a problem. I had a List<CustomObject> in C#. I needed to jumble that list…
Already did that on an extension method but wanted to know if something already existed
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
is the cast really a good idea though
i just used what they already did in what i could see 🤷♂️
Because Count is a method, not a property
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
where do I add Array.Copy() ?
is it an array or a list?
tiles
you can always just make a copied list with:
List<Tile> tilesCopy = new(tiles);```
I don't think it works with Lists
Regardless PraetorBlue already posted a much better solution for shuffling which will work infinitely better anyway
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
this one ?
Then where I do all the rest with the Casting and stuff ?
you don't?
You just use a shuffle method like https://github.com/jschiff/unity-extensions/blob/338d306ba17f86efa7beea1618ef486132e42720/Runtime/Extensions/CollectionExtensions.cs#L91
List<Tile> tilesCopy = new(tiles);
tileCopy.Shuffle();```
That's what I have in my extension method... so back to square 1 👀
yeah what's the issue with it?
Nothing but wanted to know if there's an already existing stuff to do that directly instead of writing that code
it complains
you may have to make the list yourself from the 2d array
yeah so back to square 1
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
That works yes
Do they mean to shuffle the existing array in place?
No because the array is a 2D array, so first I need to convert it into a 1D array (or a list) then Shuffle
What's the end goal here
No you don't
You could totally rewrite the shuffle algo to work with the 2D array
You can just call the shuffle method twice
Just with a tiny bit of math
Or whatever amount you need it
The only difference to this method is that you add a nested loop
I need to retrieve X elements from that list to creates mines in my Grid (It's MineSweeper)
A nested loop would shuffle each row individually, no?
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
You know a List is basically an array that automatically resizes itself, right? The behaviour is practically the same. The only difference is that you don't need to do manual work to make sure it's big enough for your data
Yes
You just change the array accesses to use / and % to get the x/y from the single index
Yep
So this ? ☝️
No, this is a flattened approach to insert values into a 2d array it seems
No shuffling is done
my brain is melting 🤣
you asked about a random element there so i answered about a random element
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
Here my goal is to get X random elements and loop over them and set their value to -1 (-1 = Mine in my MineSweeper game)
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
true
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
how do you figure that?
in the method without shuffling, you'd be randomizing across the entire board
I don't understand
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
I shuffle and take X first cells
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)
that's what I have in mind
that second approach is what im referring to here with "randomizing a lot"
Yeah I'm not doing the second one by fear of drawing the same cell multiple times and having to draw a new one again and hope it's not a duplicate
you can just loop until you find one that's not a duplicate
true but that's resource waisting imo
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
if you're worried about resources, why are you choosing to shuffle the entire board?
Why wouldn't I shuffle the entire board ?
because you only need a small random selection
to be clear im not saying the second approach doesn't potentially waste resources
So you shuffle only the X first elements ?
that would just get the first X elements but shuffled, rather than getting X random elements
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
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
and the solution that would waste the least resources (that i can think of) is way more complicated than is really necessary for this kind of question
i might be phrasing some stuff confusingly. give me a sec to get on pc to check some stuff
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
listCopyfor instance (to preserve the original list). - I need a random value between
MIN_VALUE(let's say 10) andMAX_VALUE(let's say 25) determining the amount of mines that will be present in my grid. Let's say the random gives us20. - Shuffle the whole
listCopylist 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 😄
you would not shuffle on every iteration of the loop
shuffling is already an iteration
oh yeah my bad but you will still need to get a random value between 0 and the list.Count
yeah shuffle does that too?
which shuffle already did (in your proposed case)
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
yes but not in the second approach where you need to generate a random number on every iteration, that's why I was against that apparoach
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?
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
shuffling would get more random numbers
yes, this is the only drawback compared to the other solution
Oh
I don't know the innerworking of the Shuffle so yeah you could be right on this
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
That's why I complain about Unity not having a solution for this kind of things already implemented for us to use directly
it's such a specific thing
If you just need to randomly pick out a subset of items from a pool, you don't need to shuffle the whole pool.
the new idea being just yates shuffle up to k instead of up to n
That's what we talked about I think just above ☝️
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.
maybe linq Shuffle will be lazy
Is it possible in Minesweeper to have this many mines (-1) in a row (at line 2) ? 😄
Oh so the question is actually about picking random indexes to initialize a mine sweeper game.