#archived-code-general
1 messages · Page 84 of 1
oh means like it didnt select my maxvalue for some reason 😭
i've been playing over and over again
is GetRandomValue() being called?
but none reaches my max value
yess
yes, because if you look at the documentation...
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.
.....
oh... ok. i think i got it hahaha. thank you!!
so bascially i will just set my "max value" higher
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
DAC?
Divide and conquer
i would not expect that to work
this is actually one of it's most common use cases
so I think it should work just fine
ah, I see, you sort it first
is there a method to reset a scene in unity?
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)
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...
no error whats so ever, only problem I had what that this if statement was always true
well... couse i made the same operation with foreach loop and Linq appereantly wasnt behaving the same
What the Select is doing there is converting it into a IEnumerable<bool>. Those bools can be true or false and Count just counts them. What you probably wanted to use was Where.
Or you can use Any, which can be a little faster because it stops when it finds the first one.
It makes it sound like you're picking things out of the enumerable
OH RIGHT!!!!
these names were all picked to match SQL terms, iirc
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
didnt do SQL for like 3 years so yeah... this part of a brain already did a ahrd reset on itself XD
but this logic would not fit here. I wasnt searching for first active player, but needed to know how many players ARE active
ah, this checks if there are at least two players
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()?
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.
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;
}
this would only be possible if the function had a concrete implementation
and I do not believe it has one
IList<> has no implementations. Interfaces usually don't implement their own members (and they couldn't until relatively recently)
alright thanks!
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)
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
you don't have any devices connected
Looks like you didn't enable USB debugging on your phone. ADB is the utility that allows debug communication over USB.
That's not a code issue though, #📱┃mobile would be better suited
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);
}
}
the position is where wherever the pivot point of the object is
yeah but it still points to that gray object I checked
I don't see any sense in that
why it does that
nht.transform is the transform for the object
yes
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
yes
it it set to pivot
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
hmm
there's no way that happend
wait, are there two colliders on the same object?
ah, right, it shows colliders for child objects
yeah
what happens if you deactivate it and try shooting the same ray?
still nothing
what is "nothing"?
in the raycast method, use Debug.Log to log the object you hit
do it like this
Debug.Log("Hit", nht.gameObject);
ah, right, you can just look at the name
can you show the inspector for the exhaust and bolt objects?
wait
this is the exact same situation
selected it the "bolt"
and it's the child of the right one
sure
i think i can tell which is which, but that's still hazy :p
so blue is where the ray actually hit, and then green goes to the transform
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
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
now we know lmao
hey i cannot seem to run my game on my phone. it just keeps closing. This is what the console says:
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
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
But can i create a copy without instantiate?
you are creating only a copy of the list. Your new list is full of references to the same GameObjects the old list was pointing to.
You can't.
I cant? But i can create a list of GameObjects without instantiate them
Shouldnt clone be possible too?
You cannot create a list of GameObjects without instantiating them
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())
playersList.Add(newChar);```
This is how i created my playerList without instantiate
characterPrefab is not in the scene
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
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
no it won't
unless newChar is a value-typed struct
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?
If newChar is a normal GameObject or Component reference, it will give you a list with 3 references to the same object which you have changed 3 times
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
Friction might be causing it. You can adjust it with a physics material
oh so there's friction by default even without materials
huh
alright, thanks
I assumed that it was 0 by default
Default 0 would be weird for sure 😄
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
how do i use/import splines into my project?
was a fuckup on my side
From the package manager
Its not being found (in the pkg manager)
If you can't see it there press the + and "Add by name" and use "com.unity.splines" as the package name
thanks!!
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
I think the best practice here is to separate your character object into two things:
- 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.
- 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.
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
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.
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 });
I don't like that you have CoreStateValue and VitalValue. Can they not share one type, like a MutableValue or ModifiableValue or something
They're conceptually different
"core stats" are the things you level up, like strength
"vitals" are health and stamina
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
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
health can't be levelled up?
It's derived from your core stats
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
Gave me nostalgia for Armored Core
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
This can make it interesting, gameplay wise
As long as its indicated somehow
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
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
}
}
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
Thanks alot for the reply!
POCO is something unity related?
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
Nope it's a generic term in C# (and similar to terms like POJO in the Java programming language)
Pokemon go, poco, whats the difference
(I don't get the joke)
pogo
pokemon go :p
Praetor you make me feel young
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
Nah I played Pokemon Go when it came out
i'm starting to feel old as people miss homestar runner and MrWeebl references
basically no difference
probably faster - assuming it's a plain field and not a property
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.
The lists contain classes that store a specific stat's current value
Make sense, thanks
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
You should just need 1 dictionaries at most from my understanding. VitalBase and VitalValue seem to share a lot
oh yeah, that's unexplained
Kinda false. You can hack something.
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
I have tried using those SerializableDictionary thingies before. I could give it another go..
You can make an object (Vital) which contains the base and the runtime value ?
Vital itself is the ScriptableObject that holds information describing the stat
e.g. the LocalizedString for the name and description
Then what is VitalBase ?
e.g.
a specific entity's base value for that vital
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
Can you just have Value that contains Base ?
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
I mean, make a custom inspector.
true
hey, that reminds me: i need to fix this mess
it's using a visual element with a Row flex direction
OCD intensifies
you've defined an extension method inside your class
which isn't allowed because it's not a static class
Yeah that last method is an extension method
oh
because the first parameter uses this
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?
- Make sure you have no compile errors
- Make sure the list variable is not
static - Make sure it's inside a MonoBehaviour or plain class marked
[Serializable]
- Make sure the script is added on a GameObject
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?
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
Can you show the actual code?
!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.
Ideally the whole script
Aaaand found the error.
🦆
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!! 
Will add the: - Make sure you are looking at the correct GameObject in the list.
Glad to be of service
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)
);
}
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?
Maybe you want the Splines package?
Other than that, there is Handles.DrawBezier for editor. But youd have to implement the controls yourself
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
You can draw Handles in the inspector too
Just did something like that recently
ooooooooooooo
interesting. Yeah something like that is what I'd like
that's purdy
For a long time I also assumed that Handles are for the scene view only lol
the tasteful specular highlight
Yeah had to add a gradient!
And some shadow for depth
yeah looks nice!
now make it emit a loud grinding noise as you move the handle
imagine if the unity editor made sounds as you used it
Yeah gotta have that immersion
That's so 2000's lol
i need that generic mouse click sound
You've got errors!
played once for every error, sequentially
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
I think I had some clipping issues with DrawBezier - like it was clipping in the Z weirdly. There's surely a fix for that (GUI.BeginClip etc?)
But I ended up just drawing the points with Handles.DrawAAPolyLine
You can use MakeBezierPoints to get the points without actually using DrawBezier:
https://docs.unity3d.com/ScriptReference/Handles.MakeBezierPoints.html
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?
@solemn rune TLDR; I used MakeBezierPoints + DrawAAPolyLine
I forgot to mention, the player has a circular shape as well
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
Object Pooling
thanks g
Gotcha, thanks! Fiddling with it now
I also never knew I could use Handles in the inspector.. Trying to figure out how to do that right now 🙂
Usually, I use Parent/Child for sticking object on an other dynamic object.
yes, but I want to make it actually stick to the object, because it could bounce off or just slightly not touch the object anymore after touching. I still want the player to move around it though
I just want to figure out where the jittering comes from: there's no movement, no friction, no other external forces whatsoever
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 ?
also, the planet attracts the player anyway, so there is no need to make it a child
as I said, no movement, the only force once the player is on the planet is the planet attracting the player, no friction, no gravity, rigidbodys yes and all are dynamic
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
When it comes to jittering, its often a problem with not using interpolation and/or using the wrong way of moving the rigidbody (like moving it via the transform)
Could be a camera timing issue too
Seeing a video of the current behaviour would be helpful
I suspect it might be a bit more complicated in this instance as it is bouncing off the planet and not truly jittering.
I yeah, though I just decided to scrap the idea of using a surface effector to move the player (since it looks really unrealistic and weird) so there's no jittering anymore
but now I need to find another way of moving smoothly
I think you might have force on the rigidbody that plays itself. You should use a non physics solution with a Kinematic Rigidbody.
I said all rigidbodies are dynamic before
Yeah I have no idea if effectors respect interpolation at all
Dynamic ? Kinematic is not the same ?
and I want to have them dynamic because the planets should also be moved when hit by the player
Kinematic means no force will be apply on the player.
Then you calculate yourself the force.
sorry I meant no jittering anymore my bad
It gives you the maximum amount of control.
One message removed from a suspended account.
Yeah I assumed that. So do you currently need a way of sticking to the planets since you removed the effector?
I'm sorry, a small other issue I'm facing: why is that grey outline there?
I see a lot of gray but no outlines
no I programmed the gravitational force from the planets myself, the effector was just for moving the player around the planet which well didn't seem to work smoothly
Oh that whole dark gray thing
yeah sorry I mean that grey thing
yeah
Okay. If I understand what youre saying, you need to use the planet's up vector (which you can get with (selfPos - planetPos).normalized) instead of the world's up vector in your movement calculations
it's still there even when unchecking emission
do you mean for jumping off the planet or for what? because I am doing that already
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
Yeah. So do you want to walk around the planet?
yeah, but not through controls but rather smoothly all the time
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?
wait imma make a short video
Not through controls
Yeah im lost
Try using NavMesh.SamplePosition to snap the start position to the NavMesh before you use CalculatePath
I want the player to move around the planet all the time, the only control about the game is when to jump off a planet
Ah okay so you need it to constantly rotate around the planet
well not rotate but move
I mean it's round so isn't that the same
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
im not sure i understand what you mean by this; what does snapping the start position entail?
I don't really get what you mean
what do you mean with limit its position?
My mistake - I thought youre using NavMesh.CalculatePath which is a separate method
i think you meant to reply to me
Yes
👍
Two messages saying "i dont get what you mean" 😆
all the planets attract the player, except once he hits a planet, then only that planet is attracting it
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
With limit its position I mean move it towards the position which it should be on the planet
You could make a joint that rotates around the planet for example
which joint, I already said that the suurface effector made it look weird?
Surface effector is not a joint, I mean the physics joints
https://docs.unity3d.com/Manual/Joints2D.html
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
am i crazy or should this debug statement always print out navMeshAgent enabled: True?
but like the gravitational force is already used for that, I just need a way to the move the player
ohhh
what does StopNavigating do?
but that would not really help since at some point left and right switch up
code literacy is so crazy thanks for pointing that out
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
didn't dani make a video showing the controls/movement script?
only post in one channel
Thats why I'm saying you should add a left/right force relative to the planet
Yeah I used it but for me the controls are mixed up and the camera has a vertical tilt
oh okay
I will try that tomorrow
thanks for the help
oh yeah for the material question, does somebody have an answer?
I tried it out, but the movements is jittery once more
^
oh wait the jittery movement goes away with the distance joint, interesting. thank you!
how can I check whether the player should move to the left or right? because without it it makes him change direction sometimes
You'd have to do some math when entering the planet
hmm weird now it's even jitterier than before
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
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
Just realized this could just be done with a dot product or angle check from self to planet
can't I maybe somehow check whether the current velocity is closer to aimline.left or aimline.right (aimline is a line that show up in the opposite direction to the planet)
Yeah thats pretty much what I described in the second message I think
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?
You could actually just try this cs float angle = Vector2.SignedAngle(selfVelocity, planetPos - selfPos); bool movingLeft = angle < 0;
Basically checking if the planet is left or right, relative to your velocity
(Might need to invert it to angle > 0)
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
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
Okay, that's what I've done, but he justn uses one variable so it got me confused
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?
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.
How are you moving the rigidbody?
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
Np. You probably want to enable Interpolation in the rigidbody settings too, so it looks smooth
can I ask somewhere a blender vs unity technical question?
probably #🔀┃art-asset-workflow
oh thx
How would I calculate how many degrees this dotted line should be rotated to go from one red dot to the other?
Mathf.atan2
I want it to work the same way that a gun would rotate around the player to face the mouse
Probably. Let me see
Say it praetor
Oh no
You probably don't need to know the number of degrees.
If it's a linerenderer you just set the points.
If it's an object you're rotating you just set transform.right equal to the direction from one to the other
But I suppose it depends on what you're actually doing
It's an object. Thank you though 🙏 🙏
This is what I needed
Can the direction be a vector with a magnitude of more than 1?
Sure, but that's not considered as a direction vector anymore
But does it work?
To put in transform.right? Sure
Perfect
Yes the magnitude is ignored
Wait that looks like a board game I know. Afrikan Tähti
I'm not surprised, but I had to check lol
In Danish
That's not what I am making though lol
Ahh well then it makes sense. Its designed by a Finnish person
Ah yes, of course
If this isn't the right channel to ask this question, could someone direct me to the correct one?
I don't know, but I would ask in #archived-code-advanced
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
Thanks
ah, thanks
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)
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
what returns null?
Findpath?
Yes
ok, so that implies it's getting to the end of the function
is this on a grid?
GridManager.Instance
probably yes, then!
Yeah a grid of tiles managed by GridManager
does GetNeighbors work right?
if it ALWAYS fails to go up or left, then it feels like that's the problem
I think it has something to do with GetNeighbors() script but im not sure why its not working
oh
if (currentNode.Position.x - 1 <= -1)
isn't this only true if you're out of bounds
that feels backwards
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
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
and also all the up ones have the same issue but inversed
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
ah yeah that would prob make it slightly easier to read
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
this is roughly what I did when writing the most overly fancy solution for the first homework assignment :p
the nice thing here is that this makes it easy to, say, let you move on diagonals
just add more offsets
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
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);
}
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!
"\"" 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.
so, that'll be the best way to do it, I'd say
@heady iris any clue about my issue with Debug.DrawLine? am i using it incorrectly?
do you have Gizmos enabled?
you toggle them separately in scene and game view
also, they will only live for one frame by default
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)"
Seems the list or array itself is null
As in - are you sure you actually have a list?
If it's not serialized you'll need to have created it manually
but in the inspector it shows the array with inventoryItems
Show your actual full error message and the full code if you would
I make it using this "inventoryItems = new InventoryItem[inventorySpace];"
inventoryItems[i].item would cause an exception if any element in the array was null
null.item
essentially
Yeah that too, or at least the item at index i
Thank you for the input on this @heady iris
Will give it a shot! 🙂
however, I should ask
...are you doing this to escape a string?
there might be a smarter way to do that
wdym excape a sting?
Not you, he's talking to @molten thicket
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
I'm trying to build an editor extension that format this hell:
are you trying to generate valid JSON?
or are you parsing and then pretty-printing JSON
Haha well I'm trying to:
- Remove all line breaks / spaces (Needs to be single line)
- Replace all " with /"
So the above screenshot, should end up looking like this:
"[ { \"anonymous\": false, \"inputs\": [ { \"indexed\": true, \"internalType\": \"address\", \"name\"`....
getting strong XY problem vibes here
what is the end goal?
like, where is this data going?
Quite literally just formatting as the class I use to send this through ethers.js requires the ABI to be formatted like the above
the ABI?
You could always just parse this with an existing off-the-shelf JSON parser and then spit it back out pretty-printed
Newtonsoft JSON can do this
with like 2-4 lines of code
looks like it's valid JSON already
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?
I don't see why not
ABIs are application binary interfaces 🙂
It's used in Solidity
ah, I wasn't sure if that was the right acronym here
Haha no stress!
Here's a snippet of one way to do this with Newtonsoft JSON
https://gist.github.com/frankhu-2021/b6750185b19fd4ada4ba36b099985813
under no circumstances would I recommend trying to do this manually through string parsing.
@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 😄
trying to approximate anything with string replacement is
hm
a great way to generate bug bounties
What is solidity?
Where im from (joke) ABI is what defines stuff like where return variables go and how parameters are passed to functions in C
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.
Not trying to be rude but why wouldnt i associate it with crypto lol your username if nft pixels
Is*
Sounds interesting tho
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.
I've had the email address I created when I was about 11 for more than 20 years now 😱
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
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"
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
Glad to see we're all in the same boat
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)?
It depends:
- On the data
- On the algorithm
- On whether some vertices take longer than others to process
- On how parallelized it is / can be
There's no simple answer
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.
Use Resources.Load
ty !
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?) )
and I presume id accept a string that is the filename and in the method add that to a string which is the path.
I think you should focus on ways to parallelize this.
If you can get this into an IJobParallelFor (or 3 of them,. one for each task) you will reap massive benefits.
Alright, I will do it then, thanks!
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
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
Also if it's already really fast - make sure it's worth spending your time optimizing this
I am just looking for ways to get burst and jobs maximum potential
if the whole thing runs in like 0.1ms, it's probably not worth working on this right now
otherwise you're just bikeshedding
How could I measure how much time a chunk takes to generate?
Use the profiler
Oh wait I think I got it
I was thinking about TimeSInceStartup, but this is better 😅 , thanks
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
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)
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?
I thought of loading a prefab which contains the base components of my chunk (MeshRenderer, MeshFilter, MeshCollider) insead of adding them at runtime via new GameObject(System.Type[]...)
but looking at the profiler I can tell it takes no ms doing that, so it is worthless I think
Triangle index is only valid if the collider that was hit is a MeshCollider.
dang, i just solved it, i was adding a collider manually, but apparently in the import settings, if u check generate collider it works
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
probably something like triplanar shader with vertex color per voxel "biome"
CinemachineFreeLook Jitter/Deforms during Rotation
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.
It's a cross post from #💻┃code-beginner
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...
assetbundle or addressables
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();
}
}
}```
Use animation then. With animator you can press the record button, rotate your object to where you want it, then press stop. Easy animation. In a new animator controller you can add the animation to play. That animation you can easily adjust the time it takes to rotate
Through code you can start the animation, or just have it play by itself on awake
Oh ? I haven't looked into animations yet ^^"
If it truly must be code for rotation, try a coroutine
Pretty sure this can just exist in an Update method
what i was thinking
Definitely look at that. You can look on youtube, its good to learn either way
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
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#)
use textmeshprougui
Sounds like you're using the wrong type for the variable to attach it to. Is it a TMP_Text?
this ^
make sure your "using TMPro"
its not "Text"
Ah, ok. I'll try that. Thanks.
That fixed it, thanks.

Aaaaaand now something else has gone wrong. The variable player of Score has not been assigned, apparently.
just means that a variable hasnt been assigned
are you trying to instantiate a null or something ?
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.
has the variable been assigned a value ?
I think so.
in the inspector ?
It wasn't something wrong with the score variable, it was with the player variable. Thanks.

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.
does it inherit from anything besides monobehaivour ?
score
you probably just accidentally duplicated your script
this also
Oh, wait, I fixed it. Stupid capitalization.

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.
did you decapitalise your Update method ?
Yes.
this just means you have a function/variable and a function/variable with the same name
If your !ide is set up correctly Unity methods should have a special color assigned to them. In Visual Studio they will be blue instead of yellow.
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.
So if you mistook some capitalization, it should have been yellow.
^

how to calculate needed force to reach target?
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)
Also note our !code posting guidelines
📃 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.
Yes, that is the idea
you could go with the rts box unit selection method instead of a box cast
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"
ther other method should still work
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
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
So this game (despite being top down) is Z up and on the XY plane
So, when your camera looks directly at that plane, your mouse position matches up with XY and your logic makes sense
exactly
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.
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?
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
I'LL BE DAMNED.
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
the method i was talking about used bounds 
ive never seen any tutorial use boxcast is all
Me neither, this is very specific usecase because of my game design
and how I want it to work
since 
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
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)
I kinda doubt that's the reason https://unity.huh.how/interface/unity-events/method-requirements
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartProduction : MonoBehaviour
{
public void startProduction(int itemId)
{
Debug.Log($"Click! {itemId}");
}
}
When I write the Method with a capital S at the start, It wont show up in the inspector.
well, go through my list, including the links at bottom of the paragraph
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?
@quiet briar hes right it should produce an error
you cant have functions with the same name as their enclosing type
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
The reason is probably because your method shares the same name as the class, which is not a good idea to have in general. I suggest you rename the class to StartProductionBehaviour
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?
Use multiple line renderers
now I'm rewriting the code to do this, but I thought I'd ask, maybe there are other solutions, thanks anyway for the answer
Is that expensive on the CPU?
Alright, this I will try. Thank you!
dont line renderers have gradients ? (ive never used them)
Not necessarly I think
You can do a solid color gradient
I mean
Raycast
not gradient
ll
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
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
You'd simply have extra line renderer component/objects.
thanks for the advice, I'll try now with fixed gradient, I will come back with the result, maybe it will help others
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);
}```
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
How does UpdateNameGui work?
{
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];
}
}
}
}```
How did you populate nameGuiList?
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();
}```
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
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?
uhm what are these errors? They suddenly appeared and I get them upon launch
Just some internal Unity editor UI issues
so nothing to worry about?
yes they are
weird 🤔
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(...);
}
}
No
welp
Make your own wrapper function and call that instead
im sorry whats a wrapper function again?
Just a function that calls the other function
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?
Only if they're a virtual property
i fixed my problem before
thanks though 🙂
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?
i don't really understand what's going on here
what are the short pairs of lines?
cursor locations
so should the player just snap to one of four directions?
it looks like those arrows do not point directly to the cursor locations
yes
yes like enter the gungeon
I'd just do:
Vector2 vp = Camera.main.ScreenToViewportPoint(Input.mousePosition);
int quadrant = 0;
if (vp.x > 0.5f) {
quadrant += 1;
}
if (vp.y > 0.5f) {
quadrant += 2;
}```
this will give you a number 0-3
of which quadrant you're in
yeah, that's reasonable to get a quadrant
you could also get an angle and then round it
i saw a video about this and I understood almost nothing
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.
ah, you need to change how intense gravity is for the player, then?
is this 2D or 3D?
Well I have good and bad news
although, you will probably not want to use rb.velocity.y * 1.5f as the gravity scale :p
The good news is that it's surely doing something :D
The bad is that it's not something I want to happen D:
yeah
realised that XD
what do I do?
hmmm
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.
probably just use a constant!
1.5f would be 50% more gravity
something like DoWait(0.2f).OnComplete(etc); would be nice. But it isn't actually a thing.
what's a constant?
like, 1.5f
But that's a positive value no? I want to multiply it so I goes negative when needed
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
The I'd also need a else statement to make it go back to normal no?
Weirdly enough the result of the last experience was me flying to heaven
but I still didn't made a heaven so flying to blank
if your Y velocity was negative when you set that, your gravity scale would become negative
so gravity is now flipped
Is that the correct code?
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)

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 ?
rb.gravityScale = rb.velocity.y < 0 ? 1.5f : 1f;
perhaps
that's the ternary operator: condition ? ifTrue : ifFalse
Are the spells instant or do some of the live for multiple frames?
Im thinking you could use OverlapCircle or some other query instead
There's something not correct, it's not adding 1.5f but changing the gravity to 1.5f and never going back
multiple frames.
The one that's currently causing problems is one that scales up and down in a second.
where do you run this code?
player
Ok, I dont think scaling an object, especially if its rigidbody is static, will give you trigger events
in Update?
@urban marsh Check this matrix
https://unity.huh.how/programming/physics-messages/3-trigger-matrix-2d
yes
show me your code
I think the better way to do this would be using OverlapSphere or whatever in larger and larger radiuses over time
the spell has no rigidbody, the enemy has a static rigidbody. But I understand what you mean.
Prepare yourself mentally for it, I started coding 3 days ago
!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.
use a paste site, btw
OverlapCircle would be the most reliable way here
OverlapCircleAll (the all version), right ?
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?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Again, prepare yourself to look at that, it's ugly.
But it did get the job done
looks fine

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

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
Where should I store the statement?
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
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.
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?
I don't, but I was interest about this player data concept I've seen recently
Something like this
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
It's a big 400 line context so yeah, that will be for a next project I guess
Thanks !
I've implemented the solution using OverlapCircleAll and it works ! 🙂
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)
Are you using Cinemachine?
- Double check that the scripts are on the correct objects and fields are assigned to correct objects
- Double check that the senstivity values are correct
Earliest executable code possible ?
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)
Hey – I'm looking to implement a mobile JoyStick and Panning any suggestions on how to implement before getting started? Thank you!
you're calling set destination every frame
is just gonna overwrite isStopped
put set destination inside the distance check when you want them to move, I assume when they are far from player
replace isStopped = false with set dest
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
put debug inside (distanceFromPlayer >= 35) see if it's called
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.
why are you crossposting
It's called
does it work if you replace isStopped = true to spiderMesh.SetDestination( spiderMesh.transform.position);
maybe you have 2 if conditions running at same time
do you have any other scripts controlling movement ?
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()
