#archived-code-general

1 messages · Page 84 of 1

wide fiber
#
[CreateAssetMenu(fileName = "Legs", menuName = "Position")]
public class RandomRangeSO : ScriptableObject
{
    public int minValue = 0;
    public int maxValue = 10;

    public int GetRandomValue()
    {
        return Random.Range(minValue, maxValue);
    }
}```
#

it seems not to work? did i do anything wrong?

#

pls advice 😦 i thought i had this.

heady iris
#

what does "it seems not to work" mean?

#

that could mean basically anything

wide fiber
#

oh means like it didnt select my maxvalue for some reason 😭

#

i've been playing over and over again

radiant marten
#

is GetRandomValue() being called?

wide fiber
#

but none reaches my max value

wide fiber
heady iris
#

Return a random int within [minInclusive..maxExclusive) (Read Only).

#

maxExcusive is exclusive, so for example Random.Range(0, 10) will return a value between 0 and 9, each with approximately equal probability.

wide fiber
#

oh... ok. i think i got it hahaha. thank you!!

#

so bascially i will just set my "max value" higher

heady iris
#

correct

#

add one if you intend for this to produce 0,1,2,...,8,9,10

main token
#

Hey, I got a scene that has a grid of points, and I want to find the any two points that has the least distance between them. I'm using Recursion/DAC to achieve this. However, it only seems to be accurate about 50-60% of the time. Is there anyone who can spot what I'm doing wrong?
https://gist.github.com/Cruxial0/3e450d32eecca674e5ce36f6c8d6dfe9

#

here's an image of what I mean if my explanation wasn't good enough lol

heady iris
#

DAC?

main token
#

Divide and conquer

heady iris
#

i would not expect that to work

main token
#

this is actually one of it's most common use cases

#

so I think it should work just fine

heady iris
#

ah, I see, you sort it first

heavy lynx
#

is there a method to reset a scene in unity?

hard sparrow
#

Should Audio Manager be a singleton, and have objects just do AudioManager.singleton.Play(x), or have it be a regular class and play sounds through events?

#

(or some other way)

dapper forge
#

Today at work Linq has failed me hard and I need someone to explain to me what just happened. My code looked something like this:

private List<Player> players;
public void OnPlayerDead(Player player){
  player.gameObject.SetActive(false);
  if(players.Select(p=>p.gameObject.activeSelf).Count() > 1)
    return;
  //Do some logic to indicate that last player standing won
}

So basically whenever a player dies I deactivate him and unless there is only one active player left I exit the method.
I dont see anything wrong with this code, yet it gave me a hard time couse apparently this Linq expression always returned just a collections size, like this Select() wasnt even there... wtf?????
When I switched to basic counting with foreach:

int c = 0;
foreach(Player p in players)
  if(p.gameObject.activeSelf) c++;
if(c>1)
  return;
//Do some logic...

i was getting a result i was expecting to get, which assured me that Linq was the problem, but I still dont know why the heck did it trolled me like that...

heady iris
#

Why do you believe this was the case?

#

Did you get a compiler error?

dapper forge
#

no error whats so ever, only problem I had what that this if statement was always true

dapper forge
late lion
heady iris
#

ah, yes

#

i mentally glossed over that

#

"Select" is a funky name.

late lion
#

Or you can use Any, which can be a little faster because it stops when it finds the first one.

heady iris
#

It makes it sound like you're picking things out of the enumerable

dapper forge
#

OH RIGHT!!!!

heady iris
#

these names were all picked to match SQL terms, iirc

dapper forge
#

i totaly should used where, find, os something liek that...

#

ok so now i see where the error is... a man after 8 hours of work simple forgets what Select is used for XD

heady iris
#

ha, I missed it at first too

#

"yeah, that's a predicate, so it'll filter it..."

dapper forge
dapper forge
heady iris
#

ah, this checks if there are at least two players

radiant marten
#

if I'm implementing an IList<> and it's expecting to implement CopyTo() is there a way to just pass through the original IList<> method, similarly to doing return base.CopyTo()?

final wasp
#

Does anybody know any good recources for non-grid-based runtime level editors or related things? I can't really find anything around it. Right now I'm doing mesh generation and IDK if that's gonna be the best choice for what I'm trying to do -- which is using the meshes to create the levels. I just started with it so I don't really have much but that's why I'm asking for rescources anyone knows about.

late lion
# dapper forge but this logic would not fit here. I wasnt searching for first active player, bu...

Oh, I misread. If you don't expect many items in the collection, then Where(p=>p.gameObject.activeSelf).Count() > 1 is fine. But it means it will iterate over all the elements. LINQ doesn't have a AtLeast method, but it's easy enough to implement:

public static bool AtLeast<T>(this IEnumerable<T> source, Func<T, bool> predicate, int count)
{
    var c = 0;
    foreach (var element in source)
    {
        if (predicate(element) && ++c >= count)
        {
            return true;
        }
    }
    
    return false;
}
heady iris
#

and I do not believe it has one

late lion
radiant marten
#

alright thanks!

swift falcon
#

What is this error?

CommandInvokationFailure: Unity Remote requirements check failed
D:\Unity\2022.1.11f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\adb.exe forward tcp:7201 tcp:7201

stderr[
adb.exe: error: no devices/emulators found
]
stdout[

]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
UnityEditor.Android.ADB.RunInternal (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
UnityEditor.Android.ADB.Run (System.String[] command, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
UnityEditor.Android.ADB.Run (System.String[] command, System.String errorMsg) (at <609ac2fedadc4dc2918b42b474cb9a97>:0)
regal epoch
#

hey i cannot use my phone to test my game. I've followed multiple tutorials to connect and run the game on my phone, but it just is not working. It gives some errors every time

winged tiger
simple egret
winged tiger
#

maybe yes O_O

#

anyway

#

I have 2 objects with a box collider, the gray one (the green line is pointing at it) and the one with the big collider. The problem is the yellow line it where Raycast hits, and the green one is pointint to the position of the hit object. The object with the big collider is the child of the first one. Why that happends?

#
 void Update()
    {
        RaycastHit nht;
        if (Physics.Raycast(transform.position, transform.forward, out nht, 5))
        {
            Debug.DrawLine(transform.position, nht.point,Color.yellow);
            Debug.DrawLine(transform.position, nht.transform.position,Color.green);
         }
     }
heady iris
#

the position is where wherever the pivot point of the object is

winged tiger
#

yeah but it still points to that gray object I checked

#

I don't see any sense in that

#

why it does that

heady iris
#

nht.transform is the transform for the object

winged tiger
#

yes

heady iris
#

ah, I see: so you currently have one object selected, and you were expecting the green line to be drawn to the gizmos on it

#

but it's being drawn to another object

winged tiger
#

yes

heady iris
#

is it set to Pivot, not Center?

#

top left corner of the scene view

winged tiger
#

it it set to pivot

heady iris
#

well, then your must be hitting the gray object's collider first

#

it's kind of hard to see what's going on from a single image

winged tiger
#

hmm

winged tiger
#

there's no way that happend

heady iris
#

wait, are there two colliders on the same object?

winged tiger
#

no

#

it worked like 15 minutes ago ;-;

#

and out of nowhere it stopped

heady iris
#

ah, right, it shows colliders for child objects

winged tiger
#

yeah

heady iris
#

so which one of these is "bolt"?

#

or whatever has the collider on it

winged tiger
#

this one is bolt

heady iris
#

what happens if you deactivate it and try shooting the same ray?

winged tiger
#

still nothing

heady iris
#

what is "nothing"?

winged tiger
#

wait

#

oh

heady iris
#

hmmm

#

oh, by "it" I meant the bolt

#

the thing with the thin flat collider

winged tiger
#

oh

#

works as expected

#

the ray is hitting on the ground behind

heady iris
#

in the raycast method, use Debug.Log to log the object you hit

#

do it like this

#

Debug.Log("Hit", nht.gameObject);

winged tiger
heady iris
#

ah, right, you can just look at the name

#

can you show the inspector for the exhaust and bolt objects?

winged tiger
#

wait

#

this is the exact same situation

#

selected it the "bolt"

#

and it's the child of the right one

heady iris
#

i'm kind of colorblind

#

can you make one of the lines blue?

winged tiger
#

sure

heady iris
#

i think i can tell which is which, but that's still hazy :p

winged tiger
#

blue is nht.point

heady iris
#

so blue is where the ray actually hit, and then green goes to the transform

winged tiger
#

yes

#

if unparent the "bolt" one (the blue line hit) it works

heady iris
#

ah

#

you want to get the collider you hit

#

I've never actually used transform directly from a raycast hit

#

so i didn't think of it

#

nht.collider.transform should be what you expect

winged tiger
#

oh

#

I'll try

#

oh my god

#

thank you <33

heady iris
#

i never actually knew about that behavior

#

i've always just assumed you had to get the collider out first

#

no prob :p

#

now I know, too

winged tiger
#

now we know lmao

regal epoch
#

hey i cannot seem to run my game on my phone. it just keeps closing. This is what the console says:

dull yarrow
#

How do i create a clone but wthout the references?
I have this list of GameObjects and i am copying like this enemiesListClone = new List<GameObject>(enemiesList);
But somehow, if i delete the gameobjects of the first list, the clone list objects gets deleted too

heady iris
#

yes, because you didn't make copies of the actual game objects

#

you could do something like this...

#
List<GameObject> cloned = new();

foreach (var enemy in enemiesList)
  cloned.Add(Instantiate(enemy));
#

this would create a copy of each enemy

dull yarrow
#

But can i create a copy without instantiate?

leaden ice
leaden ice
dull yarrow
# leaden ice You can't.

I cant? But i can create a list of GameObjects without instantiate them
Shouldnt clone be possible too?

leaden ice
#

the objects must have been created at some point

#

either they're in the scene at the start, or you Instantiate them (or create them with new GameObject())

dull yarrow
#
  playersList.Add(newChar);```

This is how i created my playerList without instantiate
leaden ice
#

it's a reference you had already

#

to an object that exists already (in this case, probably a prefab from your assets folder)

#

that code does not create any new objects

#

it adds a reference to an existing object to a list

#

If you want to create new objects, you must actually create the new objects

dull yarrow
#

yes, a prefab that i have
if i did thisplayersList.Add(newChar); --- > change some variable in the newChar object; playersList.Add(newChar); --- > change some variable in the newChar object; playersList.Add(newChar); --- > change some variable in the newChar object;
This will create a list of 3 objects with diferent values in the variables

leaden ice
#

unless newChar is a value-typed struct

swift falcon
#

Upon impacting with ground (landing after jump) my player experiences a sudden drop in horizontal speed (2d), doesn't seem to be anything in my code - happens even when nothing affects the object

#

any ideas what causes the issue and how to solve it?

leaden ice
#

it will not create any objects
You'd have to show more code, especially the declaration of playersList and the type that it is a list of to be sure.
But assuming it's a class and not a struct, you will not create any objects this way

hexed pecan
swift falcon
#

oh so there's friction by default even without materials

#

huh

#

alright, thanks

#

I assumed that it was 0 by default

hexed pecan
#

Apparently friction is 0.4 by default in 2D

#

Or 0.6. Did a quick google

heady iris
#

the default is gonna be a value that's physically plausible

#

so, probably not 0 :p

swift falcon
#

yeeeeah this seems really bad

#

it seems that friction is in fact, drag

hexed pecan
#

Default 0 would be weird for sure 😄

swift falcon
#

because setting it to 0 results in objects being yeeted after any amount of force is applied

#

0.4 by default btw

#

huh, weird

#

nvm

#

solved it

hot torrent
#

how do i use/import splines into my project?

swift falcon
#

was a fuckup on my side

leaden ice
hot torrent
leaden ice
hot torrent
#

thanks!!

dull yarrow
# leaden ice it will not create any objects You'd have to show more code, especially the decl...

I see what you are saying
My game have a character list that in each level the game spawns the characters of the list
Instead of a list of gameObjects, should i make a list of lets say a class with each char data, and then when i instatiate, i apply the data of the list to the instatiated objects
And when switching between levels, because i need to keep the characters data, before destroying the characters instatiated, i need to save the data of them in that first list that i created
Is this a better way of doing it?

For now i am creating a list of gameobjects the way i showed and then i instantiate them
But i am having problems to pass those objects between levels because of list copying

leaden ice
# dull yarrow I see what you are saying My game have a character list that in each level the g...

I think the best practice here is to separate your character object into two things:

  1. A pure data representation of the character. This would be a Plain Old C# Object (POCO) which has everything you need to describe the character. For example its name, current HP, max HP, experience level, whatever you want/need. Let's call this "CharacterData". It should be serializable so it can be part of your saved game data.
  2. A GameObject representation which maybe has a Character MonoBehaviour script on it. The Character script should be able to accept a "CharacterData" reference and behave/build itself according to that object. It can also modify the character data as things happen in the game. (For example the character gains experience points, that would be recorded in the character data object).

You can then have some kind of DDOL data manager script which is responsible for tracking the CharacterData objects through scene loads etc, as well as recording that data and loading it to/from save files.

When you spawn characters, you'd use some kind of identifier for the character data object and spawn your prefab and initialize it with the character data object as needed.

heady iris
#

i need to do that on my end

#

i'm adding a lot of lists of stats to my Entity class...

#

so I guess I should extract that into a nice CharacterData

leaden ice
#

The specifics of all this are really going to depend on the needs of the particular game.

#

but that's generally the approach I take.

heady iris
#

i'm making the 359432nd soulslike game

#

so i'm gonna have to save and load some of your stats

#

when you collect enough uhhhhhh beans

#

i don't like this

#

i'm trying to keep the Entity class definition pretty short

#

so this should help

#

also this leads to some of the worst lines of code I've ever seen

#

vitals.Add(new() { vital = baseVital.vital });

#

this used to be even worse: vitals.Add(new() { vital = vital.vital });

leaden ice
#

I don't like that you have CoreStateValue and VitalValue. Can they not share one type, like a MutableValue or ModifiableValue or something

heady iris
#

They're conceptually different

#

"core stats" are the things you level up, like strength

#

"vitals" are health and stamina

leaden ice
#

I think ideally you could narrow this down to like a single
List<MutableStat> or something, but yeah I have no idea how your game works

heady iris
#

They do both derive from Stat, since they all have things like names, descriptions, and icons

#

i'm gonna go hit this with a hammer until it stops making me unhappy

leaden ice
heady iris
#

It's derived from your core stats

leaden ice
#

Can't you make your health bar longer in Souls?

#

I see

heady iris
#

Yeah, but you do that by leveling vitality/vigor/whatever it is

#

i forgor

#

it's all robot-themed

#

the fun part is that all of these things are ScriptableObjects

#

i got really annoyed by enums

leaden ice
#

Gave me nostalgia for Armored Core

heady iris
#

one awkward thing is that there is now no clear definition for "health" anywhere

#

like, there's no Stats.Health

#

so, instead, I just give an entity a list of vitals that kill it if they get to zero

#

i guess this'll let me do something funky later, like an enemy that dies if it runs out of energy

hexed pecan
#

As long as its indicated somehow

heady iris
#

yeah

#

it minimizes the amount of "hard coded" stuff

#

the entity just gets...some vitals...and some core stats

#

i'll have to see how it pans out tho

high violet
#

i am trying to make a webrequest to get some data and i want that if it gets an error or something happens and i don't get the data it should re-run the function(which makes the webrequest) till it succeeds , the function is this:-

IEnumerator ObtainSheetData()
    {
        UnityWebRequest www = UnityWebRequest.Get("https://sheets.googleapis.com/v4/spreadsheets/something");
        yield return www.SendWebRequest();
        if (www.timeout > 2 || www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("error " + www.error);
            Debug.Log("Offline");
        }
        else
        {
            //Something
        }
    }
simple egret
#

Wrap all the code in this method in a while loop

#

And break; out of the loop when it succeeds

#

Or a for loop, if you want a max amount of tries before it gives up

dull yarrow
heady iris
#

Plain Old C# Class

#

basically, any time you just have a class that isn't a MonoBehaviour or something similarly special

#

oh wait, Praetor defined the acronym :p

#

it's not a unity-specific term

leaden ice
heady iris
#

oh, like that pokemon phone game

#

(please laugh)

hexed pecan
#

Pokemon go, poco, whats the difference

leaden ice
#

(I don't get the joke)

heady iris
#

pogo

leaden ice
#

oh

#

Like the sticks?

#

Pogo stick?

#

I'm old

heady iris
#

pokemon go :p

hexed pecan
#

Praetor you make me feel young

shy spire
#

Out of sheer curiosity, is constantly setting a boolean to true on updade faster or slower than checking if it is false and only setting it to true in that case

leaden ice
#

Nah I played Pokemon Go when it came out

heady iris
#

i'm starting to feel old as people miss homestar runner and MrWeebl references

leaden ice
steady moat
# heady iris i don't like this

When I see a lot dictionaries. 🫣

It might be because of wrong choice of design. People that tends to use a lot of dictionaries forget about what is class. It seems to me that you could use the Decorator pattern to wrap the concept of your stats. That being said, it is hard to judge with only a peek.

heady iris
#

oh wait, nvm, definitely faster to just set it

#

i misread

heady iris
shy spire
#

Make sense, thanks

heady iris
#

the dictionaries are there so that i can easily grab the value of a specific stat

#

I'd just make them dictionaries from the start, but you can't serialize those

steady moat
heady iris
#

oh yeah, that's unexplained

steady moat
heady iris
#

VitalBase stores information like "what's my base health and base health regen?"

#

VitalValue stores the runtime value, after computing your max health based on VitalBase and your stats

#

I could mush them together, I guess, but I kind of prefer to separate the authoring data entirely

heady iris
steady moat
heady iris
#

Vital itself is the ScriptableObject that holds information describing the stat

#

e.g. the LocalizedString for the name and description

steady moat
#

Then what is VitalBase ?

heady iris
heady iris
#

different guys might have different base health

#

also i just noticed that the Decrease Verb string is entirely wrong

#

whoops

#

i only have English strings right now anyway

steady moat
#

Can you just have Value that contains Base ?

heady iris
#

I could mush them together, yeah

#

That's how it worked originally, actually

#

It doesn't feel that much better to separate the authoring data entirely from the runtime data, so I might put it back the way it was

#

it's just annoying to have extra fields in the inspector that are gonna get clobbered in Awake

steady moat
#

I mean, make a custom inspector.

heady iris
#

true

#

hey, that reminds me: i need to fix this mess

#

it's using a visual element with a Row flex direction

hexed pecan
#

OCD intensifies

winged tiger
#

what

leaden ice
#

which isn't allowed because it's not a static class

winged tiger
#

that's all I defined

leaden ice
winged tiger
#

oh

leaden ice
#

because the first parameter uses this

winged tiger
#

ohhhh

#

didn't see it there

#

thanks

solemn rune
#

Hya. I got a public List of floats that I'm populating in a script. I dont see the List update in the inspector though. How would I manage to do this?

leaden ice
steady moat
#
  • Make sure the script is added on a GameObject
leaden ice
#

Wait I'm thinking we've misinterpreted the question. The list is showing but not changing/being populated after supposedly doing so in code perhaps?

#

Is that correct @solemn rune ?

#

Could you show the code?

solemn rune
#

Yeah correct. Also in a non static class, monoscript attached to a gameobject, no compile errors

#

public List<float> allForwardAxes; and confirmed that floats are added through allForwardAxes.Add

leaden ice
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
#

Ideally the whole script

solemn rune
#

Aaaand found the error.

steady moat
#

🦆

solemn rune
#

I'd like to pretend it was a very hard to find, very obscure problem.. But no, I was looking at the wrong gameobject (with the same object).

#

Thanks though!! sadok

steady moat
#

Will add the: - Make sure you are looking at the correct GameObject in the list.

leaden ice
heady iris
#

i got yanked away by a fire alarm

#

the ultimate exception

warm stratus
#

Hey, i have a problem, i use rectTransform to get the position of a ui element in the canvas but it depends of the scale of the UI gameObject, how can i get the position that not depends of the scale please?

private Vector2 GetSelectedLevel()
{
int levelX = (int)Mathf.Round(-levelsTransform.anchoredPosition.x / sizeMultiplier);
int levelY = (int)Mathf.Round(-levelsTransform.anchoredPosition.y / sizeMultiplier);
return new Vector2(levelX,levelY);
}

private void Actualiser()
{
    Vector2 levelSelected = - GetSelectedLevel();
    float smoothSpeed = 10f;

    levelsTransform.anchoredPosition =
        new Vector2(Mathf.Lerp(levelsTransform.anchoredPosition.x, sizeMultiplier * levelSelected.x,
                smoothSpeed * Time.deltaTime)
            , Mathf.Lerp(levelsTransform.anchoredPosition.y, sizeMultiplier * levelSelected.y, smoothSpeed * Time.deltaTime)
        );
}
solemn rune
#

I do have another question as well: Is there an (easy) way to implement a Quadratic Bezier curve in the editor? I currently use quadratic bezier curve equations (so 3 points, 1 start, 1 end and 1 control) for a couple of things, but all calculated in script, I'd love to be able to visually see the curves in the editor / be able to change the 3 points

#

I've seen all sorts of implementations over the years, but non that seem Built In. Would I need a 3rd party solution for that?

heady iris
#

bingo

#

I've only used it a little, but it's been nice so far

hexed pecan
#

Other than that, there is Handles.DrawBezier for editor. But youd have to implement the controls yourself

solemn rune
#

yeah its specifically for the editor. Looking into Handles.DrawBezier

#

well, even more specific: I need it to be in a window in the inspector

hexed pecan
#

Just did something like that recently

heady iris
#

ooooooooooooo

solemn rune
#

interesting. Yeah something like that is what I'd like

heady iris
#

that's purdy

solemn rune
#

but then quadratic not cubic

#

looking into it now

hexed pecan
#

For a long time I also assumed that Handles are for the scene view only lol

heady iris
#

the tasteful specular highlight

hexed pecan
#

And some shadow for depth

solemn rune
#

yeah looks nice!

heady iris
#

now make it emit a loud grinding noise as you move the handle

#

imagine if the unity editor made sounds as you used it

hexed pecan
#

Yeah gotta have that immersion

hexed pecan
heady iris
#

i need that generic mouse click sound

#

You've got errors!

#

played once for every error, sequentially

solemn rune
#

do you have any recourses on how to use handles (DrawBezier) on the inspector? I've scanned a few google pages, but no dice so far

hexed pecan
tacit plover
#

hey, I've been scratching my head around this issue: I want to have the player rotate around circular objects (in 2D), smooth, but also stick it to the object. the idea is that the "planets" attract the player and once he hits one of them, he is "glued" to the planet and rotates around it. The planets can also move though, so I can't just simply move the player in a circle. I figured out how to move him by adding a surface effector, but the player's movement jitters. Any ideas?

hexed pecan
#

@solemn rune TLDR; I used MakeBezierPoints + DrawAAPolyLine

tacit plover
#

I forgot to mention, the player has a circular shape as well

dark salmon
#

whats it called again like when you have 30 bullets in your scene and instead of instantiating new bullets when you shoot the game just pulls from that list

wide terrace
#

Object Pooling

dark salmon
#

thanks g

solemn rune
#

I also never knew I could use Handles in the inspector.. Trying to figure out how to do that right now 🙂

steady moat
tacit plover
#

I just want to figure out where the jittering comes from: there's no movement, no friction, no other external forces whatsoever

steady moat
#

What are the forces in play ? Do you move your Player ? Do you move your planets ? Do you have Gravity ? Do you use Rigidbody ? Is it Kinematic ?

tacit plover
#

also, the planet attracts the player anyway, so there is no need to make it a child

tacit plover
#

I want to figure out a way the player is moved around the planets in a realistic fashion, e.g. he shouldn't like move to the right, hit a planet, and then suddenly switch movement direction on the planet

hexed pecan
#

Could be a camera timing issue too

#

Seeing a video of the current behaviour would be helpful

steady moat
tacit plover
#

but now I need to find another way of moving smoothly

steady moat
#

I think you might have force on the rigidbody that plays itself. You should use a non physics solution with a Kinematic Rigidbody.

tacit plover
hexed pecan
steady moat
tacit plover
#

and I want to have them dynamic because the planets should also be moved when hit by the player

steady moat
#

Kinematic means no force will be apply on the player.

#

Then you calculate yourself the force.

tacit plover
steady moat
#

It gives you the maximum amount of control.

clear tiger
#

One message removed from a suspended account.

hexed pecan
tacit plover
#

I'm sorry, a small other issue I'm facing: why is that grey outline there?

hexed pecan
#

I see a lot of gray but no outlines

tacit plover
hexed pecan
#

Oh that whole dark gray thing

tacit plover
tacit plover
hexed pecan
tacit plover
#

it's still there even when unchecking emission

tacit plover
hexed pecan
#

For moving around the planet

#

Or maybe I don't get the issue at all lol

tacit plover
#

uhm

#

selfPos - planetPos).normalized
this is just the direction from the planet towards the player right?

#

because I want the player to move around the planet, not away

hexed pecan
#

Yeah. So do you want to walk around the planet?

tacit plover
lament bloom
#

having a bit of an issue where CalculatePath on my NavMeshAgent returns false (no complete or partial path) but just using SetDestination works perfectly as expected. is there any way i can get CalculatePath to produce the path that SetDestination is calculating and following?

tacit plover
#

wait imma make a short video

hexed pecan
#

Not through controls
Yeah im lost

tacit plover
hexed pecan
tacit plover
hexed pecan
#

Ah okay so you need it to constantly rotate around the planet

tacit plover
#

well not rotate but move

hexed pecan
#

I mean it's round so isn't that the same

tacit plover
#

but yeah if you want to call it that

#

well yes

hexed pecan
#

You can limit its position from the closest planet by directly changing its position (with rb.MovePosition), adding a force, changing the velocity, or using a Joint

#

Disable that limiting when you jump, and enable it when you get near another planet again

#

You can fade in and fade out the effect too

lament bloom
tacit plover
#

what do you mean with limit its position?

hexed pecan
lament bloom
#

i think you meant to reply to me

hexed pecan
#

Yes

lament bloom
#

👍

hexed pecan
#

Two messages saying "i dont get what you mean" 😆

tacit plover
#

all the planets attract the player, except once he hits a planet, then only that planet is attracting it

lament bloom
#

yeah im not sure why CalculatePath on the agent is failing to produce a path when SetDestination works just fine. I hoped to use the method on the agent so that it would take into account the stopping distance, but if it's failing to produce a path, it probably still isn't doing that

hexed pecan
#

You could make a joint that rotates around the planet for example

tacit plover
#

which joint, I already said that the suurface effector made it look weird?

hexed pecan
#

Not too familiar with the 2D joints but maybe a DistanceJoint2D

#

Use that to limit the distance from the planet, but also add a force towards your left/right direction, rotated by the direction from the planet

lament bloom
#

am i crazy or should this debug statement always print out navMeshAgent enabled: True?

tacit plover
#

ohhh

tacit plover
#

but that would not really help since at some point left and right switch up

lament bloom
vale karma
#

I already made a few 2D games in unity. And would say that can do stuff on my own to a certain degree. Now I wanted to make my first 3d game and because I really like Karlson the game. I thought it would be nice to add the karlson movement and just a few obsticals I got everything set up but I just cannot get the movement to work right and the the proportions are just of. Would love to get some help. Thanks

tacit plover
#

didn't dani make a video showing the controls/movement script?

shell scarab
#

only post in one channel

hexed pecan
vale karma
#

Yeah I used it but for me the controls are mixed up and the camera has a vertical tilt

tacit plover
#

oh okay

hexed pecan
tacit plover
#

I will try that tomorrow

#

thanks for the help

#

oh yeah for the material question, does somebody have an answer?

tacit plover
# hexed pecan

I tried it out, but the movements is jittery once more

tacit plover
#

oh wait the jittery movement goes away with the distance joint, interesting. thank you!

hexed pecan
#

Nice 👍

#

Are you sure though? How are you moving the rigidbody?

tacit plover
#

how can I check whether the player should move to the left or right? because without it it makes him change direction sometimes

hexed pecan
#

You'd have to do some math when entering the planet

tacit plover
#

hmm weird now it's even jitterier than before

hexed pecan
#

To see if you should keep moving left or right upon entering the planet, maybe something like this would work cs var selfNextPos = selfPos + selfVelocity * Time.fixedDeltaTime; // Predicted position var planetToSelf = selfPos - planet.position; // Direction from planet to self var planetToSelfNext = selfNextPos - planet.position; // Direction from planet to player's predicted position float angle = Vector2.SignedAngle(planetToSelf, planetToSelfNext); // Angle between current and predicted direction

#

See if angle is less or greater than 0 and make it move left or right based on that

tacit plover
#

now it's smooth but I have a new problem: when the player is exactly at 0 degrees (under the planet), he keeps moving left and right really fast

#

wait now it works

#

weird

hexed pecan
tacit plover
hexed pecan
#

Yeah thats pretty much what I described in the second message I think

vernal wharf
#

Question: I have multi-additive scenes with my first scene as the bootstrap scene, and my next scene as the game scene. Within the game scene I load the player, but for some reason the player gets loaded in the first scene (bootstrap) scene instead. How do I get my script that's in my game scene to load the player in the game scene instead of the bootstrap scene?

hexed pecan
#

Basically checking if the planet is left or right, relative to your velocity

#

(Might need to invert it to angle > 0)

lyric forge
#

So I found this tutorial I was going to look at for making a rhythm game, since I'm using a rhythm system in my current project. He used the old input system, but I use the new input system with two keys, space and enter.

#

What should I do

simple egret
#

Set up the new input system so you catch inputs in your code, like the old one

#

Create an Input Actions Asset, make an action map, add some actions. Enable code generation for the asset, create an instance in your script, subscribe to the input events, and that's pretty much it. Setup questions are better off asked in #🖱️┃input-system

lyric forge
#

Okay, that's what I've done, but he justn uses one variable so it got me confused

hushed needle
#

hello. i am new to unity and this is so weird for me. when i run into a box collider, this weird thing happen. anyone know how to fix it?

humble hinge
#

If I have a series of textures of concentric colors, and I want to procedurally create 3D-looking blob objects based on the colors. For instance, in this image, I'd want a blue blob in the center, a green blob around that, and an outer red blob, all based on the color shapes in the textures on the 3 planes. Then I could hide the outer blobs based on hit, revealing the inner blobs.
First, I thought if I could get the pixel data with world coordinates for each pixel and then spawn metaballs that are spread out on the mesh, that would work. So, maybe GetPixels would work, but my final textures are on a wide cone, rather than a plane. I looked for ways to extract world coordinates from the location of a pixel in a texture, but could not find anywhere someone had done that.
Then I thought raytracing might hold the answer, but that's very new to me and wondered if someone could point me in the right direction, if you think that may hold the answer.

hexed pecan
hushed needle
hexed pecan
# hushed needle

You should move it in FixedUpdate and with a proper physics method, either rb.AddForce, rb.velocity or rb.MovePosition

#

Currently you are using transform.position to teleport it forward. It ends up inside the collider, and it will be pushed back in the next physics update.
That leads to the jitters you showed

hushed needle
#

oh

#

thank you so much

hexed pecan
winged tiger
#

can I ask somewhere a blender vs unity technical question?

heady iris
winged tiger
#

oh thx

rustic ember
#

How would I calculate how many degrees this dotted line should be rotated to go from one red dot to the other?

rustic ember
#

I want it to work the same way that a gun would rotate around the player to face the mouse

rustic ember
hexed pecan
#

Say it praetor

rustic ember
#

Oh no

leaden ice
#

But I suppose it depends on what you're actually doing

rustic ember
#

This is what I needed

rustic ember
simple egret
#

Sure, but that's not considered as a direction vector anymore

rustic ember
#

But does it work?

simple egret
#

To put in transform.right? Sure

rustic ember
#

Perfect

leaden ice
hexed pecan
rustic ember
#

Never heard of it

#

Actually yes

#

It's called Africa's Star in my country

hexed pecan
#

I'm not surprised, but I had to check lol

rustic ember
#

In Danish

rustic ember
hexed pecan
#

Ahh well then it makes sense. Its designed by a Finnish person

rustic ember
#

Ah yes, of course

humble hinge
deep oyster
#

this doesn't really coutn as code but not sure where else to put it. Why does my editor play button look like this? I'm not using any extensions

#

you can see the button on the right is using the correct resolution

deep oyster
#

ah, thanks

rugged storm
#

hay im trying to add A* pathfinding but when it has to move left or up it just returns null, clue with whats going ? Heres my pathfinding script: https://gdl.space/apomasicac.cs

#

(I am very new to C# and this is my first time doing something like this so my code is prob a little jank)

heady iris
# heady iris e.g.

i finished refactoring (so that stats are all stored in a separate class), and it's really pleasant when, the moment you fix all the compiler errors, everything goes straight back to working perfectly

#

i guess that's a good sign, haha

rugged storm
#

Yes

heady iris
#

ok, so that implies it's getting to the end of the function

#

is this on a grid?

#

GridManager.Instance

probably yes, then!

rugged storm
#

Yeah a grid of tiles managed by GridManager

heady iris
#

does GetNeighbors work right?

#

if it ALWAYS fails to go up or left, then it feels like that's the problem

rugged storm
#

I think it has something to do with GetNeighbors() script but im not sure why its not working

heady iris
#

oh

#

if (currentNode.Position.x - 1 <= -1)

#

isn't this only true if you're out of bounds

#

that feels backwards

rugged storm
#

OH ty cuz my tired brain would not of been looking at this till tomarow before i saw that i used the wrong comparison symbol

heady iris
#

ha, no prob :p

#

I TA'd a class that taught data structures a year or so ago

#

so I saw plenty of things like that

rugged storm
#

and also all the up ones have the same issue but inversed

heady iris
#

here's how I usually phrase these things

#
if (x > 0)
if (x < width - 1)
if (y > 0)
if (y < height - 1)
#

rather than adding the -1 and +1

rugged storm
#

ah yeah that would prob make it slightly easier to read

heady iris
#

also, it would be even more readable if you just made a predicate for it

#

InBounds(int x, int y)

#

or InBounds(Vector2Int pos)

#

as desired

#

and then you can be really fancy by making a list of offsets

#
List<Vector2Int> offsets = new() { new(-1,0), new(1,0), new(0,-1), new(0,1) };
#

and then just try adding each offset to the current position

#

and checking if that's in bounds

heady iris
#

the nice thing here is that this makes it easy to, say, let you move on diagonals

#

just add more offsets

rugged storm
#

ahh, keep that in mind next time I need to do that. for now i'm stinking with what I got cuz its already written

rugged storm
#

Little extra Help, path is the list returned by Findpath() here, issue is DrawLine isnt appearing?(it is running the for loop because when i put other code after it that code executes)

        for (int i = 0; i < path.Count - 1; i++)
        {
            
            Debug.DrawLine(new Vector3(path[i].Position.x, path[i].Position.y,0), new Vector3(path[i + 1].Position.x, path[i + 1].Position.y, 0),Color.red);
        }
molten thicket
#

Hey guys,

I have a question regarding replacing characters in a string 🙂

I'm playing around with Replace()

I'm curious to know how you would replace " with \ " given \ " is used to escape the " character:

```string ImprovedABI = ABI.Replace(""", """);````

Any help would be greatly appreciated!

heady iris
#

"\"" translates to a string whose contents are "

#

\\ is how you encode a single backslash

#

so...

#

replace "\"" with "\\\""

#

you could make this a little easier to read by using single quoted strings

#

you can also use verbatim strings to simplify further

#

replace '"' with @'\"'

#

oh wait...' is for character literals in C#!

#

i forgot about that

#

Got a little mixed up with Python there.

heady iris
rugged storm
#

@heady iris any clue about my issue with Debug.DrawLine? am i using it incorrectly?

heady iris
#

do you have Gizmos enabled?

#

you toggle them separately in scene and game view

#

also, they will only live for one frame by default

rugged storm
#

Oh, how thats prob it then

#

that in fact was the problem lol the duration

pearl trench
#

Why am I getting this error "Object reference not set to an instance of an object"? I have an InventoryItem class that contains an Item class variable. I have a list of these InventoryItems and I am trying to check if the item in each InventoryItem is null or not by "if (inventoryItems[i].item == null)"

leaden ice
#

As in - are you sure you actually have a list?

#

If it's not serialized you'll need to have created it manually

pearl trench
#

but in the inspector it shows the array with inventoryItems

leaden ice
pearl trench
#

I make it using this "inventoryItems = new InventoryItem[inventorySpace];"

heady iris
#

inventoryItems[i].item would cause an exception if any element in the array was null

#

null.item

#

essentially

leaden ice
#

Yeah that too, or at least the item at index i

molten thicket
heady iris
#

however, I should ask

#

...are you doing this to escape a string?

#

there might be a smarter way to do that

pearl trench
#

wdym excape a sting?

leaden ice
heady iris
#

to escape a string is to get rid of patterns that might be meaningful in a language

for example, you might escape this:

"<b>Hello!</b>"

as

"<b>Hello!</b>"

...to make it safe to put in a webpage

#

< is the escaped form of < in HTML

molten thicket
heady iris
#

are you trying to generate valid JSON?

#

or are you parsing and then pretty-printing JSON

molten thicket
#

Haha well I'm trying to:

  1. Remove all line breaks / spaces (Needs to be single line)
  2. Replace all " with /"
#

So the above screenshot, should end up looking like this:

"[ { \"anonymous\": false, \"inputs\": [ { \"indexed\": true, \"internalType\": \"address\", \"name\"`....

heady iris
#

getting strong XY problem vibes here

#

what is the end goal?

#

like, where is this data going?

molten thicket
#

Quite literally just formatting as the class I use to send this through ethers.js requires the ABI to be formatted like the above

heady iris
#

the ABI?

leaden ice
#

Newtonsoft JSON can do this

#

with like 2-4 lines of code

#

looks like it's valid JSON already

molten thicket
#

Yeap but am trying to create an editor extension for new users to smack their ABIs in there and the extension will make it all nice and pretty for them.

I'm new to Editor Extensions - Does Newtonsoft work there as well?

leaden ice
#

I don't see why not

molten thicket
#

It's used in Solidity

heady iris
#

ah, I wasn't sure if that was the right acronym here

molten thicket
#

Haha no stress!

leaden ice
#

under no circumstances would I recommend trying to do this manually through string parsing.

molten thicket
#

@leaden ice & @heady iris

Both your solutions worked in their own ways 🙂

#

I've mixed them to create a solution that works for me

#

Thank you very much as always for your help 😄

heady iris
#

hm

#

a great way to generate bug bounties

dim spindle
molten thicket
#

Haha that's funny but also very interesting to know the different acronym meanings throughout programming @dim spindle 🙂

Solidity is a blockchain programming language. Just don't associate it to crypto and all that stuff. I'm currently playing with it to see if I can create some shape of on-chain game state. Where game servers might (potentially) no longer be required.

dim spindle
#

Not trying to be rude but why wouldnt i associate it with crypto lol your username if nft pixels

#

Is*

#

Sounds interesting tho

molten thicket
#

That's fair - I didn't think this pseudonym would live this long to be honest haha! It's similar to having an email address 'skate-dude69@hotmail.com' when you're 10 and living it after you turn 21 haha. Mistakes have been made.

leaden ice
#

I've had the email address I created when I was about 11 for more than 20 years now 😱

molten thicket
#

No way! xD

#

Is it really cringe? 😛

leaden ice
#

I cringe when I give it to someone in person or on the phone yes. but it's my go-to "spam" email so I always give it to companies etc so when they inevitably spam me it goes there

molten thicket
#

Hahahahaha

#

At least you're making it work for you

leaden ice
#

I won't say it here for obvious reasons but it's a combination of the name of a MegaMan character and just a word I thought was "badass"

quaint rock
#

im still using the same gmail i made when i was 14

#

though mostly as a spam catcher as well, with most real stuff going to my own domains email

molten thicket
#

Glad to see we're all in the same boat

glossy basin
#

Hello there, I have a optimization question here;

I have a code that generates a procedural mesh using the Jobs system and burst system

Currenty I am using a single job that creates all stuff the mesh needs (vertices, triangles and uvs)

So my question is, is this approach right? or should I split the process in 3 jobs (a job for generating vertices, another for UVs and another for triangles)?

leaden ice
#

There's no simple answer

rugged storm
#

Yo I'm not even really sure how to search this up so I'm coming here for help, how would I retrieve a specific file by name via a method that inputs the name of the file I need can that be done? In more specific I want to make method that will change the cursor image to one of many images in a folder, referring to the image by name as the argument passed into the method.

rugged storm
#

ty !

glossy basin
# leaden ice It depends: - On the data - On the algorithm - On whether some vertices take lon...

Then, repliying to your questions

-The data is a 1D array that contains block data (this is a voxel game like minecraft ) that contains an enum (Defines the block type, i.e BlockType.Stone)
-The algorithim I am using is just a single for loop that iterates through the lenght of the chunk data lenght and for setting blocks at x y z, I just get the lineal index from the loop accordingly
-The vertices output is not really big for now, maximum vertices I could possibly get is 2k+ the average is 1200
-I am currently using a Ijob instead of an IjobParallelFor, I would like to do this in parallel but since I can not read the lenght of a parallel writer native list (this is needed for calculating triangles) I can not use that (Actually my question secretly aims to repliying this especific question, so I can calculate vertices in a standard job and then setting up UVS and triangles in parallel (probably useless?) )

rugged storm
leaden ice
#

If you can get this into an IJobParallelFor (or 3 of them,. one for each task) you will reap massive benefits.

glossy basin
leaden ice
#

the job could for example write the indeces of the vertices generated for each chunk into an array for the later jobs - something like that

glossy basin
#

By the way my code is already really fast because the data generation is indeed in parallel and also process the data using a 1D array instead of 3 for loops

leaden ice
#

Also if it's already really fast - make sure it's worth spending your time optimizing this

glossy basin
#

I am just looking for ways to get burst and jobs maximum potential

leaden ice
#

if the whole thing runs in like 0.1ms, it's probably not worth working on this right now

#

otherwise you're just bikeshedding

glossy basin
leaden ice
glossy basin
#

Oh wait I think I got it

glossy basin
#

I got another question, I am generating my chunks using using GameObject newChunk = new GameObject($"Chunk{chunkCoordinates.x * 16} {chunkCoordinates.z * 16}", new System.Type[]... instead of instantiate(); I have not implemented object pooling yet for this.

I was thinking , should I go with addressables for this approach? I have never used it before, but reading through it, I imagine it can be highly beneficial at the time of creating a lot of chunks (I assume addressable is way faster than using new GameObject or instantiate) I am getting a bit of garbage collection and its not very noticeable but from time to time I can notice GC spikes on the profiler

leaden ice
#

I'm not sure I understand how addressables would be applicable here

#

Addressables are about loading existing assets at runtime

#

It's basically a more flexible and memory efficient version of Resources.Load (plus a lot more features but that's the gist of it)

tame gust
#

can anyone tell me why the hit.triangleIndex is always -1, no matter what i do.
I'm just using a raycast, and since it has a hit, it also should return the hit triangle.
For testing purposes, i used the unity primitives, cube etc. They also return -1.
It feels like a bug for me, but not sure, anyone else expierienced this?

glossy basin
#

but looking at the profiler I can tell it takes no ms doing that, so it is worthless I think

ashen yoke
tame gust
#

dang, i just solved it, i was adding a collider manually, but apparently in the import settings, if u check generate collider it works

iron urchin
#

i am looking for someone who has a really solid foundation of Marching cubes for Asteroid Generation in my project , one that would be willing to work with me to teach me more about it and how to use it
I have watched videoes but i find them to be lacking in explanation in some major areas
while i understand the idea behind marching cubes and how the faces are generated, i am having issues with understanding how to apply textures and at different depths specifically

ashen yoke
#

probably something like triplanar shader with vertex color per voxel "biome"

vagrant bramble
#

CinemachineFreeLook Jitter/Deforms during Rotation

sweet basin
#

Hey everyone, is there a way to just increase the force on my jump when I'm moving up the slope? This way, the jumping is fine when am moving upwards but if I go downwards with the additional force I jump a lot higher than I should.

dusk apex
thin kernel
#

What is a good way to load an image?

The "Resources.Load<Texture2D>()" works perfect, but my images located on the server, and Resources folder does not exists in build, so I can use it with build-in files only.
I tried to use texture.LoadImage(), but it takes way more time and memory usage for every image is insane (about 30-100mb). Is there a way to reach the same performance as with Resources.Load function, but with dynamically loaded images? I don't understand why it have such a poor performance for the exactly same task...

potent sleet
#

assetbundle or addressables

urban marsh
#

Hello everyone !
I use this code in a script attached to a prefab. It is supposed to rotate the prefab 90° in 0.3f, but the loop makes it rotate just a Fixed Update too much, which makes it rotate 96° instead, and it makes things look ugly (because the 2D prefab rotated begins vertically and is supposed to end horizontally).
I previously used a Debug.Log to display the rotationTimer, and it looks like the problem comes from have a 0.19999998s fixeddeltatine instead of a 0.2s sometimes.
How should I have this work correctly ?
I was thinking about adding a "rotationLeft" float added in the code which keep track of how much rotation has been done to make sure we do not go over the max. any other idea ?

private float rotationAngleMax = 90;
private float rotationDuration = 0.3f;
void Start() {
    isRotating = true;
    rotationSpeed = rotationAngleMax / rotationDuration;
    rotationTimer = rotationDuration;
}
void FixedUpdate() {
    // Rotation
    if (isRotating) {
        transform.Rotate(0, 0, rotationSpeed * Time.fixedDeltaTime);
        rotationTimer -= Time.fixedDeltaTime;
        if (rotationTimer <= 0) {
            isRotating = false;
            DoTheThing();
        }
    }
}```
somber ether
#

Through code you can start the animation, or just have it play by itself on awake

urban marsh
#

Oh ? I haven't looked into animations yet ^^"

somber ether
#

If it truly must be code for rotation, try a coroutine

thin aurora
ocean prawn
somber ether
#

The other guys are right about one thing, you can use Update() instead of FixedUpdate(), it may be more accurate. However, again if you are going to need precise object movements and want a good workflow for it, try animations

visual fractal
#

Hello, I'm having a problem connecting a text mesh pro to a script to change the score in a game. I try to place the text into the score slot, and it refuses to attach. (I'm a beginner to Unity but not to C#)

thin aurora
ocean prawn
#

make sure your "using TMPro"

#

its not "Text"

visual fractal
#

Ah, ok. I'll try that. Thanks.

ocean prawn
#

the text one is legacy

visual fractal
#

That fixed it, thanks.

ocean prawn
visual fractal
#

Aaaaaand now something else has gone wrong. The variable player of Score has not been assigned, apparently.

ocean prawn
#

are you trying to instantiate a null or something ?

visual fractal
#

I'm trying to get the score number to change with the distance the player has gone. It's the same piece of code as last time.

ocean prawn
visual fractal
#

I think so.

ocean prawn
#

in the inspector ?

visual fractal
#

It wasn't something wrong with the score variable, it was with the player variable. Thanks.

ocean prawn
visual fractal
#

I now feel like a beginner at code as well. The code is exactly the same as it was when it was working, and now there's an error.

#

Assets\Scripts\Score.cs(11,10): error CS0111: Type 'Score' already defines a member called 'Update' with the same parameter types.

#

I feel really dumb, not knowing what's going on.

ocean prawn
visual fractal
#

Score or Update?

#

Or both?

ocean prawn
#

score

quartz folio
visual fractal
#

Oh, wait, I fixed it. Stupid capitalization.

ocean prawn
visual fractal
#

I feel like there's something going horribly wrong with my code. It's not working at all anymore, not even an error or a warning.

ocean prawn
visual fractal
#

Yes.

ocean prawn
#

same with Start and Awake

visual fractal
#

Ah.

#

That was what was causing the problem earlier, but ok.

ocean prawn
thin aurora
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

thin aurora
#

So if you mistook some capitalization, it should have been yellow.

ocean prawn
#

^

visual fractal
#

Finally, no more errors. The game's running normally.

#

Thank you.

ocean prawn
vestal crest
#

how to calculate needed force to reach target?

slow crag
#

Hi! I've got a mathematical issue where I want to project a 3D boxcast box through a 2D selection box's representation in the world (drag-to-select from RTS games).

I've recorded a 1 minute video to explain the issue along with a visualization of the problem. I think there is one line of code missing but I can't figure out how to get it to work.

#

And here's the related code (relevant method is SelectObjectsInBox)

quartz folio
#

Also note our !code posting guidelines

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

ocean prawn
slow crag
ocean prawn
#

you could go with the rts box unit selection method instead of a box cast

slow crag
#

Imagine two units being on the same tile. One is on the ground, one is flying 10 tiles above (but same x,y position). If you were in top down and dragged a box, you'd select both of them. If you were zoomed in with the camera angled, you'd only select the ground unit. The flying unit would be out of the selection box.
That is my entire point and why I'm "overcomplicating this"

ocean prawn
#

ther other method should still work

quartz folio
#

I don't understand what space _initialMousePosition and _currentMousePosition are in, it seems to be world but it wouldn't make sense if it was ah it makes sense if this is side on

ocean prawn
#

^

#

whats MouseWorldPosition()

#

referring to

slow crag
#

Yes, they are indeed in world space

#

The reason is that you can click and hold a mouse at some position in the world, and you can pan the camera using WASD and that point will remain "sticked" to that part of the world

quartz folio
#

So this game (despite being top down) is Z up and on the XY plane

slow crag
#

yes

#

a bit confusing with all the perspective swapping, sorry

quartz folio
#

So, when your camera looks directly at that plane, your mouse position matches up with XY and your logic makes sense

slow crag
#

exactly

quartz folio
#

when it's not looking down that plane, the X and Y magnitude are nonsense

#

you want the X and Y magnitude in the local space of the camera.

slow crag
#

How can I get that? I barely got to this point, math, vectors and magnitudes confuse the crap out of me

#

Do I need to convert world coords to camera local space and then use that for the height of the box?

quartz folio
# slow crag How can I get that? I barely got to this point, math, vectors and magnitudes con...
Vector3 currentMousePositionCamera = cam.transform.InverseTransformPoint(_currentMousePosition);
Vector3 initialMousePositionCamera = cam.transform.InverseTransformPoint(_initialMousePosition);
float xSize = Mathf.Abs(currentMousePositionCamera.x - initialMousePositionCamera.x);
float ySize = Mathf.Abs(currentMousePositionCamera.y - initialMousePositionCamera.y);

Something like this

#

Presuming the camera's transform is not scaled weirdly

slow crag
#

it works.

#

thank you!

#

I hate using the word literally

#

but I've LITERALLY spent the last 3 days

#

trying to figure this out

#

I knew it was a couple lines of code but had no idea what I was conceptually looking for

#

It's still a bit off

#

but I think it'll get the job done

#

players will mostly probably select units in the "tactical" top-down mode anyway

ocean prawn
#

ive never seen any tutorial use boxcast is all

slow crag
#

Me neither, this is very specific usecase because of my game design

#

and how I want it to work

ocean prawn
#

since Okay

strange ferry
#

Hello people, I have a script in the yellow dot, and I want to get a component in the blue dot game object, but these objects are inside other objects in the scene, how do I traverse up the hierarchy only two steps? Thanks

quiet briar
#

Hi there 👋
I'm not quite sure, if this behaviour is intended: I'm trying to attach an OnClick event to a button in Unity 2022.2. It is a TextMeshPro button. I added my script, with the method I want to call on click to another game object and dragged the game object into the object selection field in the OnClick event. But here comes the strange part: I can only select methods in the corresponding scripts, which names start with lower case letters. Why tho? 🤷‍♂️
(P.S.: I'm new to unity, but not to programming)

quiet briar
#

When I write the Method with a capital S at the start, It wont show up in the inspector.

quartz folio
#

well, go through my list, including the links at bottom of the paragraph

mellow sigil
#

It's not a good idea to name methods the same as the class anyway. Does it still not show if they have a different name?

ocean prawn
#

you cant have functions with the same name as their enclosing type

pearl cypress
#

Is it possible to use SharedArrayBuffers with Unity?
So have an array in WebAssembly, and let it be shared with an array in Unity?

Thanks in advance guys

thin aurora
grizzled needle
#

Hello all, I am making a laser reflection game and I don't know how to color the line renderer after going through a color filter, it needs to be colored from that point forward.

The only reasonable solution is to color it with a gradient based on the total distance and the distance between points, is there a more straightforward solution?

grizzled needle
strange ferry
quiet briar
ocean prawn
strange ferry
#

Not necessarly I think

#

You can do a solid color gradient

#

I mean

#

Raycast

#

not gradient

#

ll

ocean prawn
#

wdym

#

i havent used the line renderers but i know you can set the gradient to fixed

#

and then just set the color keys from code

#

if you wanted straight transition

#

but maybe its not that simple with line renderers

strange ferry
#

I mean you can do a line renderer that is for example plain red color, you can also add gradients.

For line renderers you can show them in the scene view using Debug.DrawRay

#

Or do a line renderer with the exact same points in space as your raycast

dusk apex
grizzled needle
#

thanks for the advice, I'll try now with fixed gradient, I will come back with the result, maybe it will help others

regal epoch
#

im working on a project with a friend. on pc, the game looks just fine. We have an input screen where you can input all the player names. on pc, the first name is on top, then the second name just below that etc etc. on my phone, somehow the list gets filled in a completely different order. The first name is on the 4th place, the second name on the first, etc. wth is going wrong

#

the name locations have already been defined. when you input a name, the next "location" gets this name in its textfield and then appears on screen

#
    {
        if (string.IsNullOrWhiteSpace(nameInput.text))
        {
            //wrong input
            Debug.Log("Please enter a valid name");
        }
        else
        {
            string[] newNamesArray = new string[nameList.Length + 1];

            // Copy the current namesArray to the new array
            for (int i = 0; i < nameList.Length; i++)
            {
                newNamesArray[i] = nameList[i];
            }

            // Add the new name to the end of the new array
            newNamesArray[newNamesArray.Length - 1] = nameInput.text;

            // Set the namesArray to the new array
            nameList = newNamesArray;
            currentName = nameInput.text;
            Debug.Log("Added " + currentName + " to the game");

            //clear the nameinputfield
            nameInput.text = "";

            //update the gui
            UpdateNameGUI();
        }
        string nameString = string.Join(",", nameList);
        PlayerPrefs.SetString("Names", nameString);

    }```
regal epoch
#

I did some debugging. On my phone, instead of number 10 there is "test", and instead of number 7 there is "test2". These are exactly the ones that get filled in first on my phone. First the "test", then the "test2". But there is no test or test2 in the scene or in the script

regal epoch
#
    {
        for (int i = 0; i < nameGuiList.Length; i++)
        {
            nameGuiList[i].SetActive(false);
        }

        if (names.Length != 0)
        {
            for (int i = 0; i < names.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(names[i]))
                {
                    nameGuiList[i].SetActive(true);
                    nameGuiList[i].GetComponentInChildren<TMP_Text>().text = names[i];
                }
            }
        }
    }```
leaden ice
regal epoch
#

Wait i'll send the full script of this scene

#

oh nvm its over the character limit

#
    {
        //Load existing playernames
        string namesString = PlayerPrefs.GetString("Names");
        names = namesString.Split(',');
        if(names[0] == "") { Array.Resize(ref names, 0); }

        //initialize nameGuiList
        nameGuiList = GameObject.FindGameObjectsWithTag("NameGui");
        UpdateNameGUI();
    }```
leaden ice
#

Ok there's the issue

#

You're populating the list with FindGameObjectsWithTag.

You're assuming that's going to put them in hierarchy order, but there is no such guarantee of ordering

#

It can and will give you the objects in any order and it can vary across different hardware

regal epoch
#

ah okay thats sounds logical

#

is there a way to prevent this random ordering?

leaden ice
#

Populate them:

  • manually in the inspector
  • by getting a reference to their parent and iterating over them with e.g. GetChild(i)
#

Assuming they're all siblings in the hierarchy yes?

abstract nimbus
#

uhm what are these errors? They suddenly appeared and I get them upon launch

leaden ice
abstract nimbus
#

so nothing to worry about?

regal epoch
abstract nimbus
#

weird 🤔

kind niche
#

is it possible to add things to the setter of a built in variable?
for example i am trying to get the change of cursor.visible so i would want to do

visible{
  set{
    event?.invoke(...);
  }
}
kind niche
#

welp

leaden ice
#

Make your own wrapper function and call that instead

kind niche
#

im sorry whats a wrapper function again?

leaden ice
#

Just a function that calls the other function

kind niche
#

oh

#

alright then well thanks

halcyon gull
#

Hey
Trying to implement push notifications into my game and wonder what's the difference between Unity Mobile Notifications package and Firebase?

#

Or when should I use one over the other?

thin aurora
kind niche
#

i fixed my problem before
thanks though 🙂

hushed needle
#

Hello, I have a problem that I don't even know what i must learn for it. I want the direction my character is looking to change with the cursor like this:

#

Does anyone know what I need to learn for this? or what i need to do?

heady iris
#

what are the short pairs of lines?

hushed needle
heady iris
#

so should the player just snap to one of four directions?

#

it looks like those arrows do not point directly to the cursor locations

hushed needle
heady iris
#

gotcha

#

that's not too much work

#

I guess I'd just do...

leaden ice
#

this will give you a number 0-3

#

of which quadrant you're in

heady iris
#

yeah, that's reasonable to get a quadrant

hushed needle
#

oh nice

#

Thank you

heady iris
#

you could also get an angle and then round it

hushed needle
heady glade
#

I want to ask a question about coding but I'm not sure of how do I properly portray that question

#

The objective is to set the player falling speed to be faster when he's in the air

#

So he jumps normally and will fall faster than he accends because I'm multiplying the ``Rigidbody.velocity.y` when it reaches a value lower than zero.

#

The code works and I already stored the things I need in a variable, but I do not know how to apply it to the player.

heady iris
#

ah, you need to change how intense gravity is for the player, then?

#

is this 2D or 3D?

heady glade
#

2D

heady iris
#

good news: Rigidbody2D has a gravityScale field

heady glade
#

whut

#

,_,

#

that has to be a coincidence XDDD

heady glade
heady iris
#

although, you will probably not want to use rb.velocity.y * 1.5f as the gravity scale :p

heady glade
#

The good news is that it's surely doing something :D
The bad is that it's not something I want to happen D:

heady glade
#

realised that XD

#

what do I do?

#

hmmm

hard sparrow
#

Is it possible to use DOTween like a coroutine? In this case I just want to make an animation play for like 0.2 seconds then change to a different animation, and I don't want to be bothered with a coroutine.

heady iris
#

1.5f would be 50% more gravity

hard sparrow
#

something like DoWait(0.2f).OnComplete(etc); would be nice. But it isn't actually a thing.

heady glade
heady iris
#

like, 1.5f

heady glade
heady iris
#

This is the gravity scale: the intensity of gravity

#

It defaults to 1

#

It's not the acceleration caused by gravity: it's a multiplier

heady glade
heady iris
#

Right.

#

if you are falling, make gravity strong

#

otherwise, make it normal

heady glade
#

but I still didn't made a heaven so flying to blank

heady iris
#

so gravity is now flipped

heady iris
#

Your velocity should not be involved.

#

You just want to make gravity stronger if you're falling, not based on exactly how fast you're falling

#

(and this would give you negative gravity again)

heady glade
urban marsh
#

Hello everyone !
I have a little problem with some collision triggers :
the player in my game can cast some spells which create damaging areas. They instantiate a prefab, which has a trigger-collider2D, and have a script attached using OnTriggerEnter2D to find enemies hit by the zone.
I have a problem with a particular spell and some particular "enemies".
some potential targets are immobile : they have a static Rigidbody2D.
some spells create a zone which grows by scaling but do not move.
these spells do not trigger on these enemies, I guess because Unity think it does not need to check colliders between things that do not "move".
It's a problem for me, since these spells can have their damaging area touch the enemies and not deal damage.
Is there a way to have this work ?

heady iris
#

perhaps

#

that's the ternary operator: condition ? ifTrue : ifFalse

hexed pecan
#

Im thinking you could use OverlapCircle or some other query instead

heady glade
urban marsh
#

multiple frames.
The one that's currently causing problems is one that scales up and down in a second.

heady glade
hexed pecan
heady iris
hexed pecan
heady glade
heady iris
#

show me your code

leaden ice
urban marsh
heady glade
heady iris
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

use a paste site, btw

hexed pecan
urban marsh
#

OverlapCircleAll (the all version), right ?

oak idol
#

Hey guys, what is the correct way to import a video file into Unity?
With an audioclip for example we can use UnityWebRequestMultimedia.GetAudioClip() and then convert that into a clip using DownloadHandlerAudioClip.GetContent(). I could not find an equivalent for video clips.
I know we can play a video file directly using the local URL, but I need to be able to save that file locally in the persistentDataPath because we later export that file to our server. How could I go about doing that?

heady glade
heady glade
#

But it did get the job done

heady iris
#

looks fine

heady glade
heady iris
#
        if (rb.velocity.y < 0)
        {
            rb.gravityScale = rb.velocity.y < 0 ? 1.5f : 5f; // <<<
        }
heady glade
heady iris
#

you wrapped it in an if statement that only runs if Y velocity is less than zero

#

so it'll never be able to run that if velocity isn't less than 0

#

just get rid of the if statement

heady glade
#

Where should I store the statement?

heady iris
#

exactly where it is

#

just remove the if

#

and the extraneous braces, I guess

#

this will, every frame, set the gravity scale

#

no matter what

#

which is what you want

heady glade
#

Looking back, I feel like we should have made a thread UnityChanThink

#

well it's done now

heady iris
#

all good :p

#

i'd make a thread if we went on much longer

heady glade
#

there's only a little problem now, but I think I can fix it, it's not adding to the scale but changing the scale. Whoever it does change at the right time and goes back to normal.

heady iris
#

Right, you don't want to add to the scale

#

you just want to set it

#

Or do you also control the scale in another place?

heady glade
#

I don't, but I was interest about this player data concept I've seen recently

#

Something like this

heady iris
#

ah

#

I don't know the context for that exactly

#

but you could absolutely have a field called baseGravityScale

#

and then use that to calculate the gravity scale

heady glade
#

It's a big 400 line context so yeah, that will be for a next project I guess

urban marsh
reef merlin
#

Hello everyone, I made a script to rotate my character in the x and y axis to look around but it only works for the Y axis anyone have a solution? Here are my only 2 scripts (everything is well filled for Serializefield)

reef merlin
#

i don't think so

#

what is this ?

leaden ice
hexed pecan
#

Code looks ok

plush hedge
#

Earliest executable code possible ?

pearl swallow
#
void Update()
    {
        distanceFromPlayer = Vector3.Distance(player.position, transform.position);
        spiderMesh.SetDestination(player.position);

        if (distanceFromPlayer >= 35)
        {
            spiderMesh.isStopped = true;
            inRangeFire = false;
        }

        else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
        {
            spiderMesh.isStopped = false;
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = false;
        }

        else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
        {
            spiderMesh.isStopped = false;
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;

        }

        else
        {
            spiderMesh.isStopped = true;
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
        }

My game object keeps moving even though navmesh.isStopped = true. It should stop and move when within certain ranges from the player. navmesh.SetDestination (player.transform)

spark shore
#

Hey – I'm looking to implement a mobile JoyStick and Panning any suggestions on how to implement before getting started? Thank you!

potent sleet
#

is just gonna overwrite isStopped

pearl swallow
#

Oh-

#

Where would be a better place to set the destination? At Start?

potent sleet
#

replace isStopped = false with set dest

pearl swallow
#
        if (distanceFromPlayer >= 35)
        {
            spiderMesh.isStopped = true;
            inRangeFire = false;
        }

        else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
        {
            spiderMesh.SetDestination(player.position);
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = false;
        }

        else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
        {
            spiderMesh.SetDestination(player.position);
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
        }

        else
        {
            spiderMesh.isStopped = true;
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
        }

I was about to try this. So basically this?

#

No, still moving

potent sleet
vale karma
#

So i used The Karlson movement code and the movement is fine. But sadly the obsticals that I created are not solid. To make the the objects solid I give them a custom layer that works fine for my ground plane but for some reason all objects that I place on the plane are not working right.

potent sleet
potent sleet
pearl swallow
#

No

#

It kinda makes it spazz out more.

potent sleet
#

do you have any other scripts controlling movement ?

pearl swallow
#

I don't think so..

#

        if(inRangeFire == true)
        {
            if(fireCountdown <= 0)
            {
                GameObject venom = Instantiate(venomShot, venomSpot.position, transform.rotation);
                venom.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * (100f * distanceFromPlayer));
                fireCountdown = 6f / fireRate;
            }
            fireCountdown -= Time.deltaTime;
        }

This just detects the inRangeFire is true, thus it can fire.

#

And it grabs the navmesh of what its attached to at Start()