#💻┃code-beginner
1 messages · Page 338 of 1
if(isEnemy)
{
if(killcount==1)
...
}```
And yeah, an array.
oh ok got it
And yeah, an array would be easy to add here, all you're doing is assigning different audio clips each time
cant do much myself, i am new so i will try, by array you mean switch staments? or somthing else
no
public AudioSource SRC;
public AudioClip[] KillClips;
...
if (isEnemy)
{
Destroy(enemy);
Debug.Log("I'm awesome");
SRC.clip = KillClips[killcount];
SRC.Play();
++killcount;
}```
It would really be wise to go through a plain C# course if you do not know of such basics as an array
You're gonna have a bad time doing anything in Unity without that
Unless it's the kind of scenario where you're on a deadline
i know but i cant impliment it in my project. I just dont know how can i use it.
Otherwise, for yourself, there's no reason not to
yep i m learning c# and unity at same time
Well, then start thinking logically what your code does
There is a lot of repetition and you're assigning a new clip for each killcount number
What's a "numbered set of elements"? An array.
kill -> play 1 audio -> count the kill -> kill -> play 2 audio ->count the kill
Either way, I gave you an example above
yes
you have been shown exactly how to use it. I really suggest you take the time to study and understand the code given. It will help you a great deal
i tried your method using array but its not incrementing the kill count
Show what you tried
And make sure you assigned the correct audio clips in the inspector in the array
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yes i did
also checked the debug it only print 0killed ofr every kill
Is it the same instance of BulletEffect each time or different ones?
Well, you destroy the object that has the script, so of course it would be 0. An object that has it incremented to 1 is destroyed almost immediately.
bullet has the script
Or move it elsewhere
let me give it a try
It doesn't matter what has the script. What matters is that you destroy the object with the variable.
or i should make it static
Just make it static for now
so what can i do ? move thie script to new game object
ok
Static is a pretty bad solution though. You're supposed to keep kill count in some sort of a manager class or something.
it worked!
That's why I said he could move it elsewhere, but for now, if he only uses it for the audio clip, it's fine
it worked ! yippeeee
Having the bullet manage audio sources and audio clips and have them on the prefab is also pretty silly.
i will fix this
Does anyone know how to make a generic monobehaviour script? I wanted to make one, but I cant attach it to an pbject because "Names do not match"... Here is what I've got
public class ObjectPooler <T>: MonoBehaviour
where T : MonoBehaviour
You cannot make a generic MonoBehaviour script
You may create a script with a generic MonoBehaviour class, but if you want to assign it to the GameObject, you'll have to have a non-generic class derived from it
https://docs.unity3d.com/ScriptReference/Animator.SetBool.html
Why is it giving me an error? Am I missing something?
You need to configure your !ide before continuing, because it shouldn't be possible to make basic capitalisation mistakes due to having autocomplete
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Why not?
Why does this function allow me to return null? In other places (can't remember exactly where, but I think most of the time) it won't allow me to return null when it's expecting an object to be returned.
{
return null;
}```
If Character is a reference type then it can be null
is that a unity thing? I think it's on my C# module server that it won't allow stuff like that
It's a fundamental C# thing
Looks like I can't configure the one I'm using, but I found the error, sorry.
Why not?
It looks like you're getting warnings for nullable reference types, which isn't a standard configuration for Unity projects. Perhaps you enabled it via your IDE
VSCodium isn't supported.
Isn't that just a weird VS Code?
It's the Nullable Reference Types analyzer shipped with newer .NET versions.
Since your method doesn't return a Task<Character?> (indicates it might be a Character or null) you get the warning
This doesn't affect performance of the compiled code, they're a bunch of analysers that can be disabled.
Yeah so supporting it should be pretty easy but I guess Unity doesn't want to do it because it's unofficial.
Can you not follow the Vs Code configuration for it? Or do you get stuck somewhere in those instructions
ah thanks, I'll figure out how to disable those warning later then 🙂
been using Task<Character?> on my server, but I guess I don't need to then
It's an annotation hint that helps writing safer null-handling code
If you can use it, it's a helpful tool to have
if I have:
Character character = await GetPlayerStats();
and it returns null, will that throw an error or will it just assign null to character?
Sadly Unity Objects are weird and so it's less useful for Unity projects, though you can work with it there
It will just assign null
so what's the warning for then? 😛
Yeah the Unity extension isn't there and I can't set it as my IDE of choice directly, only through file association.
If you correctly use the annotation then you'll mark the method as Character?, and consumers of the method will know it can return null, and if they don't handle it a warning will show there
By annotating your code you let the IDE help you be sure you won't get unexpected null reference exceptions
By default Unity projects have none of that, so you get no help writing safer code
whats the difference?
the one under uielement is ui toolkit, which the top one is ugui ie the ui gameobjects you added to canvas gameobject
thank
anyone know how i can make it to listen
u click the drop down on Path
I'm struggling to design how I want to handle data exactly in my project. I'm trying to design a simple RPG skillset, and this is what I've come up with so far:
- A MasterAttribute script, which I then generate scriptable objects off, for the actual skills, they look like the attached pic.
- A manager script to create a defined sized array, then populate it
What I'm confused about is; In my own design I don't know how you would interact with the gameobjects (the attributes), but also with a player + enemies, how would I manage their attributes as well, seperately?
I am trying to plan a modular system that could be used for various data like currencies, stats, etc that can be extended in the specific items if needed.
Just looking for advice, this seems like a bad approach, but everything else I've seen is too simple, or hard coded...
I have this code where the playerSpeed gets decremented when this function is called.
but when running
Instead of decrementing with the given value every sec
It decrements slowly like a loading bar
i don't even know how to explain
void DecreaseSpeed(float speedDecrease)
{
playerSpeed -= speedDecrease * Time.deltaTime;
}```
Record a video if can't explain in words
I'm confused. The screenshot shows an SO, not a gameObject.
the Slide Speed Decrease
should be decrementing 4 every sec until it reaches the max timer
And in that now, gameObjects for skills is a bad idea imho.
Does anyone know if I'm able to use Sprite Editor without importing a PSB file, I created my character out of shapes inside of my scene, and... I used a lot of shapes
I want to animate it using IK, but every tutorial I see, keeps importing a PSB file, but what to do if my character was built in the scene, and not in Photoshop
I see it decreasing over time. After jumping to ~80.
So I don't see an issue..? Is the issue that it jumps to 80?
What should I do instead?
It's supposed to decrease by 4 multiplied by seconds
not decrease over time like that
Can you share an example of a tutorial that does this?
Well, you're multiplying it by delta time, so it would decrease a little bit every time.
Use inverse kinematics to move your character limbs with ease!
Rig up your 2D character in Unity using Unity's 2D animation library (creating a skeleton). Next, I'll show you how to hook up IK (inverse kinematics) to your character to perform realistic joint movements. Finally, I'll show you how to use all of this together to create great-looki...
what should i use instead?
I think it's safe to ignore that. I don't think there's any other way to null check.
Don't multiply by delta time🤷♂️
Why would you need something "instead"?
I need the value every sec tho
Assuming you call that method in update, it would decrease every frame.
Wanna learn how to make your characters come alive? Then Skeletal Animation is for you!
This video is sponsored by Unity.
You need to use Unity 2018.3 or later to use these tools.
Unity is hosting a 2D Challenge - Check it out: https://ole.unity.com/2dchallenge
● Rigging documentation: https://bit.ly/2S1Xn04
● IK documentation: https://bit.l...
How would I lock a function from being called multiple times at nearly the same exact time?
I had a bool in it that returns if it's true, but that's too slow it seems?
I looked up how lock in C# works, but that's not allowed in an async function
{
// Don't allow this to be called again until we get a response
if (waitingForCombatLogs)
{
return;
}
waitingForCombatLogs = true;```
If you want it to only decrease once a second, you should either make a timer or use a coroutine.
It's not being called in update straight away but rather with an if statement
Wdym by lock? Are you multithreading?
the function can get called from multiple places (at the same time)
not multithreading as far as I know
but it still got called 2x at the same time somehow
wait maybe something else went wrong 🤔
I think you can skip the sprite editor step and go for the bone editor. Follow the manual:
https://docs.unity3d.com/Packages/com.unity.2d.animation@1.0/manual/index.html
Code executes line by line on the same thread. A function can't be called from 2 places at the same time.
yeah it's just getting called again really fast, but it completes the first time
so I have some other error somewhere
My mistake, I meant SO
On second thought you might need sprites, as it seems to create meshes from them. You don't need a Photoshop for that, there are free open source image editors, like gimp.
async function run on a new thread not?
Depends on how you call them. Unity overrides the normal way async works such that they run on the main thread.
I have Photoshop, but I already created my character in the scene view ( Hierarchy )
Well, it might take more effort to make it work instead of recreating in an image editor.
I really doubt it, I've spent a whole week on it, so it's more than just a hand full of sprites, it's.... colossal
where or how can I find some humanly readable information on that? 😛
it's roughly 140 shapes... I don't want to recreate this lol
it started off with me just messing around, and I fell in love with it
Unity manual. There isn't too much to know though. Basically, you can think that async in unity is always on the main thread. One of the only exceptions is Task.Run afaik.
I may have goofed... I'll figure it out nw, thanks for your help @teal viper
you can specify the thread it runs on
TaskScheduler.FromCurrentSynchronizationContext()
will run on the current thread
Does that mean async in unity does nothing? Or does it still run async but just on the same thread? As in, it gets executed in between other lines of code?
It's still async, just sharing a thread
Yes, it will run on the same thread at different times, like a coroutine.
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Gunscript: https://gdl.space/cihagudawu.cs
Enemy take damage script: https://gdl.space/axivupakev.cpp
Spawning Script: https://gdl.space/yufuwoxove.http
I am having a problem when I spawn a enemy and kill it, it will kill all the active enemies
any ideas on how to solve it?
yes, dont have health as a static variable
you have used a static variable because you thought it made your life easier instead of thinking about what you need to do
that what should i do sensei 😭
do the job properly instead of trying to implement shortcuts which will come back and bite you in the arse
so i decrease the health manually from the gun script?
you use GetComponent to get the correct TakeDamage instance for THAT enemy, then call the method on that
can u give an example in 1-2 line of code? i dont understnad ;-;
you mean can I write to code for you?, No
no no, just an example that does not relate to my code
i fucked around to find out but couldnt find out 😦
ok
OnCollisionEnter(Collision other) {
TakeDamage td = other.gameObject.GetComponent<TakeDamage>();
td.TakeEnemyDmg(5f);
}
if(hit) GetComponent
Hey still working on my movement script rn I am having the issue that my player is falling way to slow but If I add more mass to my player it will simply jump less high instead of actually falling quicker
code: https://paste.ofcode.org/39xPsVPu2uWPmCXyMTTRFJV
i have tried some stuff with changing y velocity but couldnt figure something out that worked
go to project settings / Physics / Increase gravity to ur liking
idk if that is preffered or not but i did that for my game
ty dint know that existed lmao
lol me too before i created my current game
its kinda working now just on landing my player object gets stuck in the ground instead of sliding further or just being able to move further
But increasing physics gravity will also affect the jump height, gravity works both ways just like irl
playerSpeed -= 12f * Time.deltaTime;
It's not multiplying by 12
but keeps decrementing by one
help
just increase the jump poewr
and the gravity
Ye but now if I increase the Jump power and increase gravity falling will actually go faster and the jumpheight wont change
you'll need to show more !code than that
if I tune the vallues
its not happening with me
is it normal for a button to get pressed when i'm pressing space bar in flappy bird, when i press the button the music changes once when i then hit space bar the button gets pressed for a period of time, i can even see the color changing
fixed it by just lowering the drag XD
oh nice
{
if (current == 1)
{
source.Stop();
sourceTwo.Play();
}
else if (current == 2)
{
sourceTwo.Stop();
sourceThree.Play();
}
else if (current == 3)
{
sourceThree.Stop();
source.Play();
}
if (current == 1)
{
current = 2;
}
else if (current == 2)
{
current = 3;
}
else if (current == 3)
{
current = 1;
}
}```
this is the code to change the music
The function(I replaced it with 12 to see if it works)
void DecreaseSpeed(float speedDecrease)
{
playerSpeed -= speedDecrease * Time.deltaTime;
}
here's how it's called
else if (isSliding)
{
SlideMovement();
slideTimer +=Time.deltaTime;
if (slideTimer <= maxSlideTimer) { DecreaseSpeed(slideSpeedDecrease); }
if (slideTimer >= maxSlideTimer)
{
isSliding = false;
}
}
man, please learn to program. !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
{
myRigidbody.velocity = Vector2.up * flapStrenght;
this.gameObject.GetComponent<SpriteRenderer>().sprite = FlappingBird;
source.PlayOneShot(clip);
timer = 0;
}```this is the code to flap the bird
switch statements would be better
changing the gravity is a solution.. but this kinda throws off the entire project.. all ur forces will need adjusted..
i prefer to add a downwards force when the player isn't grounded... u can just tack on a bit of extra gravity
gravitySim += playerSettings.gravity * Time.deltaTime;``` ofc mines a character controller.. but the same could work for a rigidbody.. by adding it to the velocity
they are just better then if else towers on the eyes and are better for preformence
this.gameObject.GetComponent<SpriteRenderer>().sprite = FlappingBird;
just a tip, you should cache this variable in awake() or start() so ur not calling GetComponent everytime u press space
tried this but then again the jumpheight was in the way for me so for now this is my solution maybe I wil add this later ty tho
nothing there tell me what playerSpeed is before and after the method. Learn to Debug your code
thanks Sensei its works now
when I jump I cancel out the Y velocity so it doesn't interfere with teh jump logic
basically just set the .y to zero
I do the same idk for some reason it wasnt really working maybe I just dint have the right vallues or something
no need to be factious
oh okay.. well if the gravity solution works for u, roll with it
The playerSpeed should be decremented by 12 or whatever value i put every second
but instead it just
decrements by one
@dreamy junco
whatever[] source;
public void changeMusic()
{
source[current].Stop();
current++;
if (current >= source.Length) current = 0;
source[current].Play();
}
thx
don't just copy/paste, take some time to think about the code and understand it
yeah i'm bad at progaming and thats better but the problem with the button beeing pressed when i press the spacebar isn't gone
why would a button be pressed with the spacebar ?
i don't know when i press the button once it changes the music once but every time after that it gets pressed when i press the space bar
like 2 seconds long after i pressed it
that makes no sense, a button is pressed on an OnClick event, that has nothing to do with the spacebar
even the color of the button changes is that a bug
it's like i would press the button but with the space bar
I cannot imagine it is a bug, it sounds more like a problem with your keyboard
the problem with the score and the bool isn't solved yet, too
tbh, it feels like you are blundering around in the dark. You should take some time to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you for the help
@dreamy junco This is an accessibility feature, to interact with UI using the keyboard.
https://docs.unity3d.com/Manual/UIE-Keyboard-Events.html
The Toggle and Button classes listen for Enter and Spacebar key presses as replacement actions for mouse clicks.
The reason it starts happening only after you click on a button is because you're moving the focus to that button by doing that, and then it starts listening to keyboard events.
good point, I hadn't thought of that
oh ok thank you
i have this code that looks for players in the scene, so that monsters can then choose a random player and follow them, problem is if someone late joins, or not just late join, whoever isnt first would miss out on being tracked and added to this hashset because it runs in awake method, i could simply run it in update as well but i feel like there gotta be a more effecient method, like only when a new player is summoned/joins or leaves would it update this, how can i approach such a solution?
Script (just in case it is needed): https://gdl.space/orafuyibeb.cs
Make the players register themselves with this script in their own OnEnable method
(make it a Singleton)
How can I make a referencable object to a script with the use of the editor? Like this 'pop up' is a template for different types of problems, that implements the interface IProblem. like StudentsConfusedProblem... I want toi have the popup to be easily interchangable between probleems. Hoped public IProblem problem worked, but its not showing up in the editor. Or do I have to hardcode it.
Unity won't serialize an interface type.
It's not a UnityEngine.Object type (duh, it's an interface!) and it's not one of the other types Unity allows you to serialize (e.g. int, or a [System.Serializable] class)
There are a few ways to deal with this
One would be to make an abstract class. This is appropriate if everything that implements IProblem is going to be a behaviour or a scriptable object
You can also use something like https://github.com/Thundernerd/Unity3D-SerializableInterface.
why specifically OnEnable method and not for example awake? and why make it a singleton?
it's reasonable if you also want to un-register in OnDisable
why is it that when i want to print an int by itself i have to go int.tostring but if i want to do a string and and int i dont have to write dostring?
beacuse you're probably using the + operator
doesnt the player object get destroyed when disconnecting?
does that turn the int into a string implicitly or
There are three + operators that involve strings
string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);
so you can add a string to literally anything
it just calls ToString() on the object
This also works fine, though:
Debug.Log(123);
Debug.Log can take an object, which it then calls ToString() on
If you have a method that only takes a string, then it will not accept an integer: there is no implicit (i.e. automatic) conversion from int to string
show me the problem you are having
Surely, you can
im not having a problem
E.g. in your own class
but yes, you can both:
- define your own
+operator - define an implicit conversion to
string(which can just callToString()if you want)
Yes, have a public operator like +, -, * or / in e.g. your class
public struct SmoothFloat
{
public float value;
public float target;
private float velocity;
public float time;
public float Update()
{
value = UnityEngine.Mathf.SmoothDamp(value, target, ref velocity, time);
return value;
}
public void Set(float target)
{
this.target = target;
}
public static implicit operator float(SmoothFloat self)
{
return self.value;
}
}
an example of the latter
public static MyClass operator +(MyClass a, MyClass b) =>
a.variable + b.variable;
public static MyClass operator -(MyClass a, MyClass b) =>
a.variable - b.variable;
public static MyClass operator *(MyClass a, MyClass b) =>
a.variable * b.variable;
public static MyClass operator /(MyClass a, MyClass b) =>
a.variable / b.variable;
You may usually need to override the ToString method
E.g. you have a class Vector2Float, and you want it to be printed as (x, y)
public override string ToString() => $"({x}, {y})";
before I try to build there is no error, after I build it sends me the eror shown in the vid, it isnt even right since the game plays fine and the error is wrong wince I have a script with the name shadowcaster blah blah
dont know if this fits in this channel but why wont the hub let me create a new project?
select an orgenisation
exactly under your curser
ooh
ok ty
didnt know i had to do that
thought i can just leave it if im working alone
oh it was my cursor lol
Hey guys, quick question. I'm using the navmesh system to move my player, and i did the boot logic for my game in a way where i create my player in a different scene from where my gameplay actually happens.
So.. there is no navmesh whenever i create my PlayerCharacter, how can i go around that problem?
lmao
You can wait to enable the NavMeshAgent until after you've loaded a scene with some actual navmesh data in it
yall please help
I don't know what this class is.
I'm guessing it's something that is editor-only, and thus does not exist when you build the game
i can find only one hit, which is a deleted GitHub Gist
which does look like an editor script
You can see its code at the start of the video (it's an editor script)
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
if you're using it to set things up at runtime, you'll need to either make this class available at runtime (very easy if it ShadowCaster2DCreator doesn't rely on editor classes!) or do the setup ahead of time
hi guys I'm very noob and following a tutorial on hex cell generation, making the splat map for the textures currently. is there a way to do something other than a simple fade between two values? like instead of a simple gradient have the two color params be lerped with a noise mask as the factor?
TriangulateEdgeStrip(e1, color1, e2, color2, hasRoad);
so that you get a noisy transition?
consider applying a lerp or smoothstep function whose start and end values are adjusted by noise
Whenever you send a struct to a new function, is a new one created or is it the same one? Wierd question but I'm planning on using something called ActionInfo containing alot of data (mostly static) so Im debating on whether to use a struct or a class for this.
structs are value types
you pass it by value, so a copy of the struct goes on the stack
(rather than a copy of the reference, for reference types!)
structs are always copied by value. The exception would be is if you use in, out or ref for the parameter
If it's a ton of data -- yep (:
in is a reasonable choice if you have a big struct you'd like to pass to something
interesting ive never used in before
ill look it up
it's basically the opposite of out. you're not allowed to modify it inside the function.
whereas out requires you to modify it
thanks ill go with this
(so that it is provably assigned to!)
thanks for the reply - why would it be the start and end values that are adjusted by noise, wouldn't it be the range in between? I would like for e1 to be fully color1 and e2 to be fully color 2, and have the range in between be a noisy transition
actually, i might instead just use the noise to modify the value
float noisePower = 0.5f - Mathf.Abs(0.5f - value); // we don't want to go out of the 0..1 range
float noisyValue = value + Random.Range(-noisePower, noisePower);
That ensures that 0 and 1 aren't touched
0.5 can get remapped to 0..1
0.25 can get remapped to 0..0.5
I was thinking of that because that's how I'd change where the transition happens.
If you smoothstep between 0 and 0.1, then you get a very rapid transition to color 2, for example
public void StartAction(in ActionInfo actionInfo)
If i passed it to this iterator below would it still be the same struct? It said iterators cant have in out or ref so I have to make a function
private IEnumerator HandleAction(ActionInfo actionInfo)
you would need the iterator to also take it as an in parameter
and since you can't... no
can someone help me again? i made another try using another logic to make the snake game and make an ienumerator to make the snake movement and make an startroutine but the unity editor is saying the that the variable is declared but not used
hi did someon knows where can i find good 2d assets for unity
the unity editor is saying the that the variable is declared but not used
Which variable? Share the full error?
also that sounds like a warning, not an error
The Unity asset store
Also this logic is flawed you are always setting position to 0. If you go down line by line you will see what i mean.
IEnumerator MoveSnake()
{
yield return new WaitForSeconds(DelayStep);
Vector3 nexPos = Vector3.zero;
switch (MoveDirection)
{
case Direction.UP:
nexPos = Vector3.up;
break;
case Direction.DOWN:
nexPos = Vector3.down;
break;
case Direction.LEFT:
nexPos = Vector3.left;
break;
case Direction RIGHT:
nexPos = Vector3.right;
break;
}
nexPos *= step;
Head.position += nexPos;
StartCoroutine("MoveSnake");
}
Also dont have Ienumerators in update.
its saying the ienumerator variable
that's not a variable
that's a local function
and yeah
you put your coroutine INSIDE Update
why would you do that?
That also means it's not going to work with StartCoroutine.
i also put the coroutine in star update
no you didn't
you put a StartCoroutine call in Start
the coroutine itself you put inside Update
What is me missing ? :{ Is this not how u do it? I have a popup that needs to spawn on the position of the gameObject. :c
but still spawns in the middle of the screen.
public class StudentManager : MonoBehaviour
{
public Popup popup;
// Start is called before the first frame update
void Start()
{
Invoke("startProblem", 3);
}
public void startProblem()
{
popup.ShowPopup();
positionPopup();
}
public void positionPopup()
{
popup.transform.position = gameObject.transform.position + new Vector3(0, 1, 0);
}
You're mixing up world space positions with UI/Canvas positions
they do not live in the same coordinate space
How would it be better then?
Everything inside the { } of Update is inside Update. Don't put functions inside other functions.
it should be:
class A
{
void Method1()
{
}
void Method2()
{
}
}``` BUt you have this:
```cs
class A
{
void Method1()
{
void Method2()
{
}
}
}```
don't do that
don't out methods inside other methods.
oh i think i get...i have to put the ienumerator outside the update method right?
IEnumerator and void are return types for the methods.
The actual things are called functions or methods
you do not HAVE to, it just makes no sense NOT to
how do I make a character follow the player like in pokemon heartgold and to change its mesh while following pls help
If you were following someone irl, how would you do it?
silently
ok, smartarse, how would you do it physically
I just wanted to try creating my first game but I'm getting frustrated with it
Sure, frustration is common when you first learn programming
if you start too complex too early, it will happen
that is because the word 'just' should never be used in developement, there is no 'just'
haha yeah if search the words just want/ed to in this discord, quite interesting results
i don't get it
exactly, and that is why you are frustrated. Using the word 'just' implies that is is easy and simple, believe me there is nothing easy or simple about game development
@unique gust btw async methods make ur code look cleaner than ienumerators
bet?
in this context i think itll look more modular and cleaner than startcoroutine(...aidadadjashd,..)
my opinion
Unity doesnt handle async as graceful as Coroutines
it does in Unity 2023+ with Awaitable class
they made updates to make it work better
yes
I'm a little confused, I think that where I live, the courses aren't that good, let's say, and that's what makes me frustrated
I've literally just turned 2 200 line classes into sync/async methods, they are now both > 1,000 lines of code and look like shite, apart from being a nightmare to debug
theres youtube and alot of tutorials there
can i have a snippet
It's these tutorials that are driving me crazy and creating these crazy codes
YouTube tutorials in general aren't very good
everybody starts with spaghetti codes
it's the sad state of things - and honestly the most entertaining ones usually get to the top of the YouTube charts, not the good ones
i started using events instead of simple method classes and in the end i got lost
then i learned the true value of events
kinda exaggerating
sure, here is one method split into 2 to allow both sync and async
public void Scene(Scene scene)
{
Task t = new Task(async () => {
IsDone = false;
await SceneAsync(scene);
IsDone = true;
});
if (isAsync)
t.Start(TaskScheduler.FromCurrentSynchronizationContext());
else
t.RunSynchronously(TaskScheduler.FromCurrentSynchronizationContext());
}
async Task SceneAsync(Scene scene)
{
if (scene == null || !scene.IsValid())
{
Serialize.Serializer.Log("Missing or invalid scene");
return;
}
components.Clear();
for (int i = 0; i < fileHeader.objHeaders.Count; i++)
{
Serialize.ObjHeader oh = fileHeader.objHeaders[i];
if (oh.objType == Serialize.ObjHeader.ObjType.GameObject)
{
await makeGameObject(oh);
}
}
for (int i = 0; i < fileHeader.objHeaders.Count; i++)
{
Serialize.ObjHeader oh = fileHeader.objHeaders[i];
if (oh.objType == Serialize.ObjHeader.ObjType.GameObject)
{
GameObject gameObject = await completeGameObject(oh);
if (gameObject.transform.parent == null)
{
SceneManager.MoveGameObjectToScene(gameObject, scene);
}
}
}
endLoad();
Serialize.Object.Clear();
}
I would track the one I have to follow
and you would do that how? by keeping a set distance behind?
ok thats a monster
yes
Ok, so thats what you do in your code, you keep the following object a set distance behind your player. See that wasn't so hard was it?
there is a difference in coding certain rules and requirements have to be fulfilled
That is one of many, my beautiful code now looks like shite
and what was the ienumerator solution
embed a progress float and implement a progress callback
for a loading screen>?
for save and load, yes
I am making an upgrade system for my game. My current idea is to create a scriptable object that holds a struct array with the data of each upgrade. For example: ```cs
[System.Serializable]
struct UpgradeData {
public int upgradeID = 0;
public string upgradeName = "name"
}
public UpgradeData[] upgradeData;
good plan
Would this be an efficient way to create this, or am I using arrays wrong?
also an index to know which upgrade is current
array is fine if you don't need to add/remove additional upgradeData at runtime
As a variable in the struct? Cause that's what the upgradeID is for
no next to your array so youi know which one to use
I can't figure out this Input string was not in a correct format error. Parse takes a string, which is what I gave it. https://hastebin.com/share/uyohogazub.csharp
Ah,
[SerializeField] private TextMeshProUGUI textbox;
change to TMP_InputField
if it's just a text field why are you trying to parse it, you are the only one that can change it's contents
have you tried actually printing textbox.text before parse
thats not the error though, the error is this line
im just trying to turn my int into a string
but anyway, the same goes, use TMP_Text for text fields
Because either firstNumber or secondNumber is not something that you can parse
Whatever it is, it's not an int
what is that print showing ?
use tryparse and apply invarient culture
sorry im turning a string into an int
Yes we can see that
we can see that
and i checked both thier types and they are strings
But whatever you're passing to it isn't an int
It can't parse whatever you're giving it
what inside the string is the problem
So that's why the suggestion was to log it and see what it is
not that its a string
So that we can see why it's not able to parse into an int
because he is using TextMeshProUGUI which has a null terminator
yeah but do *they * know that
I think I said it, twice
a null terminator? that'd be surprising
I already changed it to that TMP_Text and it didnt fix it
as you say, bold of you to assume they read anything said
changing the type of the variable doesn't change the component you are using
harsh but true
some weird whitespace, on the other hand
i already tried Trim()
There's a weird garbage character that the InputField throws in at the end of the text component that doesn't get removed with .Trim()
Maybe consider logging the value and showing it now..
a non-breaking space, perhaps
Where are you getting your string from
you would think they listen by now lol
they even had the print method
TextMeshProUGUI.text != TMP_Text.text
bro I have logged it, im having to respond to other people trying to help give me a second
whats the difference actaully?
I always use TextmeshproUGUI
alr would've took 2 seconds to show what it print
TMP_Text is the shared parent class of both TextMeshPro and TextMeshProUGUI
You can use that type to hold both kinds of TextMeshPros
so i have strings in the Parse is that not what parse takes? I swear I looked at the docs
as I said, UGui.text contains the null string terminator
TextMeshProUGUI does not override the text property, so TMP_Text.text and TextMeshProUGUI are doing the exact same thing. Are you suggesting that TextMeshProUGUI.text and TextMeshPro.text behave differently?
Did I mention TextMeshPro ?
and, actually, looking at how text is implemented...
private string InternalTextBackingArrayToString()
{
char[] array = new char[m_TextBackingArray.Count];
for (int i = 0; i < m_TextBackingArray.Capacity; i++)
{
char c = (char)m_TextBackingArray[i];
if (c == '\0')
{
break;
}
array[i] = c;
}
m_IsTextBackingStringDirty = false;
return new string(array);
}
It explicitly does not include a null terminator
what do you think this is? if (c == '\0')
the textbox
It's the content of the string that everyone's having a discussion about.
It may not be a number
ah, but array will contain null characters in any indices that weren't assigned to
so even though we never assign a null terminator, they'll at least exist
the only thing coudl be whitespace, but I tried Trim() already,l Fen mentioned nonbreaking whitespace?
Iterate over the string and log the actual codepoint of each character
this will reveal anything particularly funny
see https://stackoverflow.com/a/13894142 for an example
If this is just a static TMP_Text, why are you trying to parse it? Is this an input field
No one is saying you aren't passing a string. The string needs to contain an integer.
int.Parse("Cheese and Bacon Omelette") is going to throw that error
because "Cheese and Bacon Omelette" is not an integer
yeah I know, I understand I just looked each char in the array and there is a soace at the start
it would be useful to see the string first, yes
beg to differ, it's a 10
trim says it removes leading whitespace
see if there are zero width spaces
It is absolutely critical to know: Is this string coming from the TextMeshProUGUI component of a TMP_InputField
no
Maybe show your implementation (how you're using trim)
so why are you not using TryParse ?
Maybe it isn't a number at all, whatsoever.
this has to happen, Its not something to try
Important note:
"" is also not an integer. If the string is empty, that's also a parse failure
you have still failed to actually show us the string you're trying to parse
but if it goes wrong it goes bang! and so does your game
It's a secret 🙂
no its just that I explained it, but here a screenshot. I said it has a leading whitespace heres the string when I enter 14
so its blank?
this is individual characters
no its (whitespace) 1 4
Or some non printable character
its just that trim isnt removing that first character
thats the problem, I know why parse doesnt work now
Maybe it isn't a whitespace character?
It could also be something that displays as whitespace, but isn't actually or \t
Cast the character to int in the print
strongly suggest you to see the code of the char by casting it to int
https://stackoverflow.com/questions/239103/convert-char-to-int-in-c-sharp
Can you show more of the code, including the print statements?
its 8203, how do I find the character that represents that? is it unicode?
Get the complete details on Unicode character U+200B on FileFormat.Info
ha, I knew it (:
where is this string coming from?
@swift crag
And where is the content of that coming from
Because if you just typed it in then why not just use that value instead of getting it from the text element
no its being input from my buttons that I clicked
the buttons have a monbehaviour with the value they add to that textbox
sounds like the text starts out with a single zero width space in it, instead of being actually empty
so I can just clear that textbox on awake?
but why put them in the textbox instead of a string directly?
then just display string in textbox..
lemme try that
Why does it have that zero width space to begin when?
just...don't have a zero width space in the text component to begin with (:
thats the dream
click the text field in the inspector
hit backspace
gone
the cursor winds up moving forwards slightly when i erase a zero-width space, amusingly
dumb question but does your TextInput have any validation set on it?
it's not a TMP_InputField
it sounds like they're just appending characters as they click on buttons
yes many validations, but the error is gone now so either i removed an intial zerowidth or clearing it at awake worked
i will find out which
setting it to empty on awake is what worked
no idea why its starting with a zerowdith thing
so are you actually using a TMP_InputField, then...?
if not, i'm not clear where "validations" would be
why when i die my dead animation still in a loop?
Probably because you never stop it anywhere
"Loop Time" is a property of the animation clip
how can i do that?
Usually by transitioning out of it whenever a condition is met
I want to move this object to the left. What's the easiest way to do that?
transform.position += Vector3.left
Two bools is not a great way to represent the state of your thing!
For example:
RunningLeft = true and RunningRight = false means you're going left
RunningLeft = false and RunningRight = true means you're going right
RunningLeft = true and RunningRight = true means ????
RunningLeft = false and RunningRight = false means ????
If you just use a single bool it would be better:
RunningRight = true means you're going right
RunningRight = false means you're going left
Okay, makes sense. Thanks
RunningLeft = true and RunningRight = true means ????
or, if you want something more generalized...
Vector3 moveDir = Vector3.right;
public void Flip() {
moveDir *= -1;
}
Quaternion.LookRotation(Vector3.zero)
Logically, would your eyes implode?
I think that's how you achieve nirvana

Usually by transitioning out of it whenever a condition is met
ok
can u teach me how do that?
The same way you transitioned into it
but out of it instead
I managed to do this but how do I make it follow at a set distance and stay behind and not get away from the player
depends how do you move it now in the first place
Okay thanks yall for the help, I did get it working still don't know why theres a zerowidth whitespace thing, but I don't have time to care.
Hey guys, I have this global Array in class A, there are a few methods refered to it, and there are a few methods calls those methods.
Now ...
In another class called class B I wanna call a method which process this Array from class A, but this Array is currently only contain 0s, now I want to change a few elements of this Array.
Can I override or something like that to this Array ?
I move it based on a timer
I'm getting this error, but my script doesn't reference an object?
my bad, i didint get it
doesnt explain How you move it exactly
You're not checking if your raycast hit anything
so basically I have a timer and use ecm and it cycles through the meshes to create a walk cycle as it is moving
if (detection.collider != null) {
// you hit something
}
else {
// you didn't hit anything
}```
Either detection or detection.collider is null
detection is struct 😦
indeed but we can also secretly do this because of operator magic:
if (detection) {
// you hit something
}
else {
// you didn't hit anything
}```
From the docs
This function returns a RaycastHit2D object with a reference to the Collider that is hit by the ray (the Collider property of the result will be NULL if nothing was hit)
Then one of the two possibilities is thereby impossible
Leaving only one culprit!
well, unless we put a ? 😮

so what do you think?
idk .. if you using a lerp or some type of smoothing, increase how fast it "catchesup"
hey guys i am trying to make a 2d game but when i implemented the wall jump the player continuously started flipping can you help me solve it. it would be a great help to me if you guys can help me out as i dont know about cooding much. here are the scripts i used
If you use Navmesh agent increase acceleration/speed
how to make it stay backwards of the player and keep distance constant
I mean you put this code in Update:
if (!isWalljumping)
{
controller.Flip();
}```
So of course it's going to flip every frame as long as you aren't currently walljumping! It's doing exactly what you told it to do!
make it follow a point behind the player
Show your implementation (what you've tried)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ECM.Components;
using ECM.Walkthrough.MovementRelativeToCamera;
public class PokemonWalkCycle : MonoBehaviour
{
[SerializeField]
MeshFilter mf;
[SerializeField]
float timer, timerMax;
Mesh mesh;
[SerializeField]
Mesh[] meshes;
[SerializeField]
int meshCount;
[SerializeField]
MyCharacterController mcc;
[SerializeField]
Rigidbody rb;
bool moving;
// Start is called before the first frame update
void Start()
{
mesh = mf.mesh;
meshCount = 0;
moving = false;
}
// Update is called once per frame
void Update()
{
if (rb.velocity.magnitude > 0)
{
moving = true;
}
else
{
moving = false;
}
if (moving)
{
if (timer > timerMax)
{
mf.mesh = meshes[meshCount];
meshCount++;
if (meshCount >= meshes.Length)
{
meshCount = 0;
}
timer = 0;
}
else
{
timer += Time.deltaTime;
}
}
else
{
mf.mesh = meshes[0];
}
}
}
this is the code
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also using ECM.Components; 😵💫
ye it is easy character controller basically a character controller
it is one only I am using that only
please format the code at least
but if i change it to this
is this what follows player ? doesnt do anything it seems @buoyant finch
what makes you think this code is right either?
no it keeps a track of which mesh the system is on when switching
why are showing this then ?
for my ref
we asked for the implementation you currently have for follow
this tutorial
Learn how to add wall sliding and wall jumping to your game in Unity!
Source code: https://gist.github.com/bendux/b6d7745ad66b3d48ef197a9d261dc8f6
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
...
Clearly the isWallJumping bool is not in and of itself the right indicator to decide when to flip your character. You want to flip them when you jump off the wall, right? Do it then and not in Update.
I don't have the follow function
Yhea but look at his flip code
It's nothing like yours
gotcha
His flip code actually has conditions etc.
start with a navmesh then
You can't just mix and match some complicated 2D controller script you found with some random tutorial you found. Not without understanding the code.
slowly fix the issue of being directly behind
ok but how do I make it stay behind only and at a fixed distance
mine also has
start experimenting
eg. SetDestination to a point behind player, make sure speed/acceleration is fast enough
you probably at some point might need figure out if you need a DOT product
so how can i fix it , i am really trying to understand it
Does Unity automatically unroll loops and if not is there a way to make it do it automatically without doing it manually?
In general, no.
For Jobs code in very specific circumstances using the Burst compiler, yes https://docs.unity3d.com/Packages/com.unity.burst@1.7/manual/docs/OptimizationGuidelines.html#loop-vectorization
@wintry quarry 
I'm just not sure how to explain to you in a way you can understand
I mentioned here: #💻┃code-beginner message
the real answer is to think about what your code is doing and reconcile how this flip logic works and call it appropriately as needed.
With the way this is set up, "TurnAround" goes back to false after it's turned to true, because the gameobject turns around, mean the "detection.collider" is null. Anyone know how I can keep the bool true?
with this little context it's hard to say anything
we don't jknow how those variables are used, or why they're even needed
Is there a reason you need this TurnAround variable at all? WHy not just flip the character right then and there?
I need to flip the character and make them move in the opposite direction
Ok that doesn't answer this question
Why not just make a Flip() function that does just that, and call it here
That doesn't make a lot of sense to me
Because I'm using bools to determine which way the character should move
You're overcomplicating it my friend
ill try thanks for the help
Vector3 moveDirection = Vector3.right;
void Flip() {
moveDirection *= -1;
NakedManSprite.flipX = !NakedManSprite.flipX;
}
void Update() {
transform.Translate(moveDirection * speed * Time.deltaTime);
// Raycast here
if (detection.collider != null) {
Flip();
}
}```
Simple
if you want a bool for facing left/right and different speeds?
Vector3 moveDirection = Vector3.right;
float speed;
bool runningAway = false;
void Flip() {
moveDirection *= -1;
NakedManSprite.flipX = !NakedManSprite.flipX;
facingRight = !facingRight;
speed = runningAway ? RunAwaySpeed : NormalSpeed;
}
void Update() {
transform.Translate(moveDirection * speed * Time.deltaTime);
// Raycast here
if (detection.collider != null) {
Flip();
}
}```
speed = runningAway ? RunAwaySpeed : NormalSpeed;
What do the "?" and ":" do?
This is equivalent to:
if (runningAway) {
speed = RunAwaySpeed;
}
else {
speed = NormalSpeed;
}```
it's saying "if runningAway use RunAwaySpeed. Otherwise NormalSpeed"
aahhh okay, thanks
if runningAway is true...
it's the only ternary operator in C#!
(hence it's often just called a "ternary")
it has three arguments. compare this to the more common unary (1 thing) and binary (2 things) operators
-3 is unary minus; 1 + 5 is binary plus
hey I just want to check I'm understanding a particularly stupid bug correctly: the screenshotted code was intended to set occupied to true if worker.myHex is equal to hex. Is it correct that what it actually does is sets worker.myHex = hex, then returns true if it did so successfully?
hey yall im having a weird issue with my character movement, every time i want him to jump he just goes flying whenever i hold down the space bar. here's the code anyone know whats the issue?
here's the code
(its a 2D platformer with a 3D model for reference)
public class PlayerMovement : MonoBehaviour
{
int moveSpeed = 10;
int jumpForce = 5;
public void Update()
{
if (Input.GetKey(KeyCode.D))
{
GetComponent<Animator>().SetBool("RunForward", true);
GetComponent<Animator>().SetBool("Idle", false);
moveSpeed = 10;
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
}
if (Input.GetKey(KeyCode.A))
{
GetComponent<Animator>().SetBool("WalkBack", true);
GetComponent<Animator>().SetBool("Idle", false);
moveSpeed = 5;
transform.Translate(Vector3.back * Time.deltaTime * moveSpeed);
}
if (Input.GetKey(KeyCode.Space))
{
GetComponent<Animator>().SetTrigger("Jump");
GetComponent<Rigidbody>().AddForce(Vector2.up * jumpForce);
}
= returns the assigned value
== is for comparison
= is assignment
it doesn't return a boolean, and it definitely can't "fail"
needs == not =
so if (some non-boolean) returns true... always
yes
however, if it's a unity object, it can implicitly convert to a bool
so your code assigns hex to worker.myhex, then runs the following block if hex is a valid unity object
cool, thanks
(assuming hex is a unity object here)
otherwise it's probably going to be a compile error because that's not a bool
why do you always over explain stuff?
yeah, I just found that missing =, which was causing two different weird behaviors and got curious about how exactly that incorrect code was being read
because the user asked about the exact behavior of this code
that explanation was in fact what I was looking for
but look at their level, all you do is confuse by adding information they could not posibly absorb
I disagree. She always explains it really well, and explaining more is always better than not explaining enough.
why some times i need spam space to my player jump? is it a delay?
we'll need to see the code
there are a few possibilities
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
indeed (:
You are probably reading input in FixedUpdate
nooo my reply
input should only be read in Update
anyone knows how to make an IRL timer for the skyboxes?
DateTime.Now gives you the current real life time
as in, adjusting the skybox based on the time on the player's computer?
It's going to be in the C# documentation.
You can ask DateTime for things like "what hour is it?"
Basically:
double normalizedTimeOfDay = DateTime.Now.TimeOfDay.TotalHours / 24.0;
gives you a 0-1 value for current time of day, where 0 and 1 are midnight and 0.5 is noon
Thanks!
Or actually I guess you can just use:
double normalizedTimeOfDay = DateTime.Now.TimeOfDay.TotalDays;
void Jump()
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
anim.SetBool("isJump", true);
}
```
that one to jump
this is not the code where you read your input
so it's not that helpful to us
we're concerned about when you jump not how you jump
i.e. we care about when Jump is called
void FixedUpdate()
{
Move();
Attack();
if(isGrounded == true)
{
addJumps = 1;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
else
{
if(Input.GetButtonDown("Jump") && addJumps > 0)
{
addJumps--;
Jump();
}
}
that one?
right so exactly like I said
You're reading input in FixedUpdate
and input should only be read in Update
otherwise you will miss input, as you are seeing.
it's because Input.GetButtonDown is true for one frame
but FixedUpdate can run any number of times per frame (including zero)
and how can i fix it?
re-read praetor's post
Move your input handling to Update of course
at a high framerate, you'll have many frames between each FixedUpdate, so most of your inputs will get missed if you check them in FixedUpdate
damn comment every line
the problem is that in the the if statement about the jump button you can just spam space bar
you should jump only when the player is on the ground
You also probably want getKeyDown(), which only checks when it's first pressed
you're mixing up Transform.Translate movement with Rigidbody motion. You should pick one and stick to it, it's not going to work out well with this mixing and matching
i see
ok so i changed it to transform.translate movement to match the rest but now it just teleports the player upwards instead of a normal jump
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Animator>().SetTrigger("Jump");
transform.Translate(Vector2.up * jumpForce);
}
Well yeah you're only moving it for a single frame
If you want physics, use physics
otherwise, you have to do everything yourself
Excuse me why can't I insert elements in this SO ?
void Update()
{
if(isGrounded == true)
{
addJumps = 1;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
else
{
if(Input.GetButtonDown("Jump") && addJumps > 0)
{
addJumps--;
Jump();
}
}
}
like this?
sure
I mean clearly you've made some basic syntax error
probably mismatched brackets or something
Can't tell you more without seeing the code
GetButtonDown method is repeated twice.
You can write it once and check the boolean in it
it worked, tysm guys 😄
Because cannot serialize multi dimensional arrays
Oh ...
One 1D array is okay but anything more than that is no no ?
indeed, you would need to wrap them in structs/classes to make multi dimensional
I have a class, say it's called A, in there I have a 2D array, a few methods work with this array.
In another class called B, I call a method from class A to process the array.
But the array right now is a bunch of 0s, now I want a few elements to be 1 or 2 or something, so how can I "override" that original array ?
is B inherited from A ?
No :(((
then you cannot override you can only change or replace the original
Monster
If you want B to modify that array, you'd need public methods in A for doing so. Like SetArray(int x, int y, int value) { }
And if you want B to have it's own copy of the array you would need to clone it by using someting like BlockCopy
One thing that gets done often is collapsing 2D arrays down to 1D forms. As long as you know the X size of the array, you can "remake" the 2D array from a 1D array/list
Okay ...
Not really, both Arrays and Lists are reference types so you still need some form of clone mechanism
This kind of a 1D array should still store a struct, as you'll need both its item and position
I mean you can represent a 2D array with a 1D array as long as you know the first dimension's size
It's still pretty uncomfortable if done this way
Sure, but when the constraints prevent a multidimensional array or jagged array then this is one alternative
hey i manage to fix that issue somehow but now some time my player get stuck in a place or his front face get inverted
this is the code i am using
@brazen canyon If you want a 2d array editable in the inspector
class MySo : ScriptableObject {
public MyStruct[] myStructs;
}
[Serializable]
public struct MyStruct {
public int[] myInts;
}
Please, consider sending huge code blocks using one of the sites listed below !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hm ...
Okay I got it
Thank you
"Hm" doesn't seem convincing enough
Okay
How about "Grrr" or "Rawrrr"
a powerful website for storing and sharing text and code snippets. completely free and open source.
Sounds better now. You sure got what they meant.
Yeah ...
That's what I sound like when I went crazy
here is another code for physics stuff
a powerful website for storing and sharing text and code snippets. completely free and open source.
is there any way you can help me with this one?
or should i just change my whole code for wall jump
string split is easy way of getting variables from text but is it good for large files
maybe there better ways
no string split is not a good way
so what would be better
it depends what kind of information and what file format we're talking about
just text file
that is meaningless
what format is the text in
what information are you trying to get from it?
json is "just a text file"
but you'd use a Json parser for it
What's the issue? Does your player get stuck at the end, and you cannot move him?
yes
each with same info
Why don't you use json for it?
and some time the front face get inverted
what if i want do stuff manually
It's a bad idea. Anyway, I would split it using
yourText.Split(Environment.NewLine);
like this
So you have a custom format.
so basically what i was doing most of time
can you show an example of the data?
then you manually write a parser for your custom data format.
just i guess if i predefine specific function to each line it will perform better
at the cost of no futher compatibility
at a basic level a parser should be a state machine
you are always expecting some kind of input in each state
Would it be improper or unnecessary to add data to gameObjects using scripts? So for example, if I want a gameObject to be considered "deformable", would I make a script called "isDeformable" which has nothing in it except fields like deformRadius and deformMagnitude, and attach it to the object?
Seems quite normal to me
And how long has it taken to write a custom solution, when other formats like json or binary are already solved? Longer than any performance difference, if you somehow manage to make one faster
that is what all monobehaviours are, unity would not be usable without them
The reason why you cannot move is, probably, because of your isWalljumping value not being properly assigned, as you're checking for it before moving
if (!isWalljumping)
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
It's not bad for performance. If it's just a data container class and is not being getcomponented over and over unnecessarily, then it's all good
Okay, sweet. I'm looking to getComponent it only upon collision enter, which in my circumstance won't be called often
is there any way to fix it 
Oh, sorry, [replied](#💻┃code-beginner message) to the wrong person
Yes, you should assign it correctly
Let me have a look at it
So, isWallJumping depends on wallJumpingCounter and isWallSliding
yes
Pretty hard to say without debugging
isWallJumping is just set to true when wallJumpingCounter > 0f
And then it's set to 0f, which makes isWallJumping not be able to be set to true again
walJumpingCounter is just increased when isWallSliding
i am also not sure either 😭 is just try to follow this tutorialhttps://youtu.be/O6VX6Ro7EtA?si=-zIn3cJFi2k5GIdx
Learn how to add wall sliding and wall jumping to your game in Unity!
Source code: https://gist.github.com/bendux/b6d7745ad66b3d48ef197a9d261dc8f6
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
...
So have you just copied the code from there?
not much try to combine this with code
so should i rewrite the code becaues i am trying gor hours to solve these issue ? D:
Well, can isWallSliding even be true for a single frame?
It's set to false in WallJump right after it's set to true in WallSlide
Oh, this might be it
hmm...honestly i dont really know
ooh
Let me think how to start
There is this line, which invokes the method StopWallJumping after a certain amount of seconds
Invoke(nameof(StopWallJumping), wallJumpingDuration);
This method is the only one which sets isWallJumping to false
private void StopWallJumping()
{
isWalljumping = false;
}
Which makes the player be able to move, as there is a condition for it
But if isWallSliding is true, isWallSliding is set to false and the method gets cancelled.
CancelInvoke(nameof(StopWallJumping));
This way, isWallJumping is not set to false
The boolean can be updated just when the Jump key is pressed
But if isWallSliding is true the next frame, it doesn't update the boolean, assuming your Updaste runs more often than 2.5 times per second
That's the condition, which assigns isWallSliding to true
if (IsWalled() && !controller.m_Grounded && horizontalMove !=0f)
Although, horizontalMove is, probably, 0
And that's the only place isWallSliding is assigned to true
Anyway, you gotta check out those booleans and see
As I have previously mentioned, hard to say without debugging, as for me
oky.... ill try my best to fix it this explain a lot of things thanks for your help 😄
Right, reply to the previous messages and/or create a thread if you find anything or need a more proper explanation on the things mentioned
okiii
and thanks again for your help
How can I change a PP volume's value in code? I tried this but didn't work:
public void EnableCameraBlur()
{
if (m_CameraVolume.profile.TryGetSettings(out DepthOfField depthOfField))
{
FloatParameter param = new FloatParameter();
param.value = 0.1f;
depthOfField.focalLength = param;
}
}
You need to modify the exisitng parameter.
replacing it means that other code is looking at the old float parameter
I can't directly set focalLength to a float value because it's of type FloatParameter
right, so set flocalLength.value = ...
Hello guys! I`m doing a FSM and I have a EnemyFactory to store all the states available, like this image. I want to create StateFactory to derive from the base and use it in the Manager, but when I do, the IDE says the State does not exist. But if I create it in BaseFactory and override it in the child, still does not work. :/
Any ideas? Thanks a lot!
you would have to show the code
but based on your diagram
it seems like you have a variable of type EnemyStateFactory which wouldn't have a "Runaway" field
I don't know if it is enough 😅
I don't even know if I am doing it the best way, I just wanted to create a baseFactory that I could override with the States needed.
E.g. The RunawayState becomes the RunState with the override
If you only treat any instances of FugitiveEnemy as the base class, then you'll not have access to the Runaway variable that FugitiveEnemy has
its stuck on applcation.enterplaymode ?
Do you mean the "States" inside the Start()?
I don't know what you're referring to in your original question. you need to show us the actual problem
the IDE says the State does not exist
List out the code where that error is occurring, because there you're asking for something that doesn't exist in the base class, so the ref variable probably needs to be cast to the child class to get access to it
Oh, I think I did not explain it very well 😓
Show the code that produced the error.
If you want to access members from a derived class, you must downcast to that class.
This usually indicates that you have a design problem
Does EnemyStateFactory have a function Runaway()?
You want to use polymorphism so that different kinds of enemies can do different things
instead of directly telling the enemy "go into the Runaway state!", perhaps you should be able to say "hey, you got startled!"
different kinds of enemies can respond differently
also, this factory appears to do nothing
No, because I did not declare it in the Base, just in the child Factory.
Enemy doesn't have Runaway, FugitiveEnemy does. So you must make a new temp variable that is fugitiveEnemy as FugitiveEnemy and then you'll have access to it. That new temp var will be null if the enemy is not derived from FugitiveEnemy, so check that before using it
why not like a Dictionary<string, BaseState> then you can just make a function like enemy.GetState("Runaway")
if you do want to downcast:
if (enemy is FugitiveEnemy fugitiveEnemy) {
fugitiveEnemy.DoSomethingSpecific();
}
this combines the cast and the validity check
Even better
I tried, but I had problems with the dictionary, conflict when 2 enemies was on the scene. Probably my implementation of the Dictionary.
Cool, I'm gonna study more about downcast. Thank you guys so much!
probably just an error in your implementation, yes
I think it was because Enemy is the Father and it was responsible for create the Dictionary. When I put 2 enemies on the scene, it created the states in the same Dictionary with the same keys... Then I thought about override the Factory and here I am 😅
i'm not sure you understand what you're doing here...
When I put 2 enemies on the scene, it created the states in the same Dictionary with the same keys
If it is an instance variable then each will have their own Dictionary
i don't see a reason to have factories and all sorts of other contraptions
But yeah this is like
Someone read a "Best practices for enterprise Java" book from 1998 and tried to apply the practices to Unity in 2024
just make multiple kinds of enemies that have some common methods in their parent class
Startle(), for example
a RunawayEnemy can respond by fleeing
a CombatEnemy can respond by shooting at you
Neither do I, apparently 😅
if I build my game, will playerprefs still work?
Should. It will go off of the same registry entries
I have that. It is the Enemy and the FugitiveEnemy. I think I mixed up many concepts together... I think I`m gonna start over with a different approach
So much that I can't even explain to you guys 😅
Having multiple enemy classes is fine, but the decision making for each enemy type needs to be self contained in each class. So when an outside manager class tells an enemy to act, it doesn't need to know what type of enemy it is. It just operates on methods that are in the base class, and anything unique to the child classes isn't something the manager class ever touches
why doesn't this play the sound
I believe the player and editor store PlayerPrefs in different places on Windows
- Is the code even running?
- Is the audio source attached to the object which is destroyed?
code is running and yes
Well you're destroying the audio source
But it'll certainly work the same
so of course it won't play
well i thought it would play and then it would get destory
why would it?
you just said "Destroy this game object"
Your code says to destroy it right now
Nope, its starting to play and then is being destroyed in the same frame
"who killed hannibal" meme, essentially 🙂
nah, you quickly understood the issue once we explained it
Running into a weird issue. Not particularly familiar with Unity yet so I thought i'd check. I'm trying to attach a script to a gameobject (probably the camera), but I can't even get a "hello world" output to work on the "Awake()" or "Start()" functions. "Update()" will output the Debug.log statements I added in, but the other two functions don't seem to be called at all. I ran through a lot of the suggested checks, but nothing seems to be working. Am i missing something?
Also Hi
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You probably spelled something wrong or put something in the wrong place
I had other stuff but it's literally barebones now. Sure one sec.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestAwakeStart : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("Starting Start in Test Script!");
print("Printing Start in Test Script!");
}
void Awake()
{
Debug.Log("Starting Awake in Test Script!");
print("Printing Awake in Test Script!");
}
// Update is called once per frame
void Update()
{
Debug.Log("Updated");
}
}
no compiler errors
This looks fine.
Make sure you saved the code, and then show a screenshot from the unity editor including the console window and the inspector
Are you using AddComponent at runtime to give the camera that script?
yep it's saved. I've tried multiple variations. Like I said the "updated" output posts to the console when I build the app, but the start/awake functions don't.
I just dragged the script onto the camera (and checked that it's enabled)
Not even getting warnings in the console when its' running
please share the screenshot(s)
Yeah, I thimk maybe you didn't save changes to the script, like PraetorBlue mentioned
and so you're testing with an older version htat doesn't have awake and start in it with the debug logs
just stuff like this
or the tidal wave of "Updated" is washing away the messages
show the whole editor
I mean you have thousands of logs here
how do you know this isn't printed?
It's probably near the beginning
Definitely saved changes to the script, because I've tried removing the "updated" output and putting it back in, and the changes were reflected when I built the app. I checked the beginning, and also did a search through the logs. For example I can search for "updated" and it will come up in the console. But searching for "awake" will come up with nothing
hang on i'll comment it out and recompile it to clean up the console if you want
This is being tested remotely on a headset, right?
I wonder if you miss the first frame's messages.
Consider the following:
IEnumerator Start() {
yield return new WaitForSeconds(1f);
print("Start!");
}
replace your Start method with this and observe how it behaves
Yeah I'm testing it directly on my quest 3. It's going to be a MR app
hmm, if I check "wait for managed debugger" in the build settings would that cover it?
I'm not familiar with remote debugging/playing in general
i believe you'd only want that if you were doing actual script debugging
Well I seem to recall that if i didn't have "script debugging" checked I wasn't getting any messages in the console at all that I put out
Hmm maybe if Initiailize a variable or something in the start and then output it in updated it will tell me if it's getting run
Have you tried doing this?
i was getting a compiler error. Something about not being able to do it with a void function?
replace the entire Start method with the code I provided
note how it returns IEnumerator, not void
Aha they are getting run apparently...
I tried the other method first since I was in the middle of it
i set the value for a variable in each of them, then outputted the variable in "updated"
it's showing both are apparently running, they just weren't giving me any actual output
how does one pass a reference to an object in the scene to a prefab but the prefab is the player and istn spawner via a spawner than u could just pass down the reference from there, the player is netwrok object that spawns in via thew netwrok manager whne a client connects
What object do you need a reference to?
you can log the current frame (Time.frameCount) in Update to find out when you start getting log messages
the health bar, i know a solution is to just spawn a canvas with the health bar, like have it as a part of the player prefab but i feel liek thats messy, if i just run the players health script locally it should also work?
Honestly the health bar should have a reference to the player, not the other way around
but yeah you can have it as part of the player prefab
but if i want a diff solution
also a healthj bar definitely isn't something that needs to be networked
Is this a thing there's only one of?
Or is it a health bar floating on a player's head or something? Or what
no its just your typical health bar top left of the screen ui element that doesnt move or change except more heads appear, each head being an icon for the lives
so yes only one of it
You could use GameObject.FindWithTag or the Singleton pattern
yeah, since it's a trivial thing to find
You have to start worrying if you have multiple things you could find
it definitely should be a local client only thing
(and only one of them is right)
well.. tag is easier but i dont want a tag just for that
so ill go with singleton?
but if its like this, then well i already got a tag for the player
You have "I don't want to do that" to every other solution so why not.
Yes I recommend this. It's the perfect case for the "observer pattern"
oh boy.. even more new stuff that i have to get to know
Yeaaa.... to be honest if you haven't mastered juggling references yet, I wouldn't be dabbling in multiplayer, but that's just me.
I'm trying to exclude certain items from my post processing layer (for when you examine an item) so I made a child camera on my main camera which renders a seperate layer for certain objects and set the Clear Flags to Don't clear. Problem is that the entire item is not visible anymore.
What did you set the depth of each camera to?
They're both at 0
ah that was the problem
thanks!
im getting null reference exceptions from this script but if i unpause in play mode and ignore them it works as intedned, i dont know why im getting them https://paste.ofcode.org/EqSwLUWCmELt96kd72EfyB
there is one, and only one, cause for a null reference exception
something on that line is null
so either volumeSliderValue is null or AudioManager,instance.masterVolume is null
AudioManager.instance could be null.
the other one can't be null volumeSliderValue
even if it was a reference-typed variable that could be null, it wouldn't matter -- you're just assigning something into it
string whatever = null;
whatever = "hi";
i put a cylinder in my game scene that i'm going to use as like a wheel of fortune board.
the problem i'm having is that it seems like the rotation is clamped from -180 to 180.
why is this happening?
also here is the current code i'm using in an update function:
// Calculate the rotation angle
float rotationAngle = rotationSpeed * Time.deltaTime;
// Apply rotation to the object's local rotation
transform.localRotation *= Quaternion.Euler(rotationAngle, 0f, 0f);
if i added an if statement checking if audio manager is null would that fix things?
you have a problem when you try to use the member access operator on a null reference!
foo.bar.baz
foo or bar being null here would trigger an exception