#archived-code-general
1 messages ยท Page 232 of 1
but it's solved??
then you will have no issues
everything is solved right there
your character is very noticabley jumping and jittering up and down, and the screen is moving very unevenly
that's only because I'm very zoomed in and slowed the movement down
to show that pixels are properly aligned globally
hmm, whereas in the earlier screenshot, where you did not align
i didn't really noticed the alignment zoomed out
unlike the example where the camera is rotated:
everyone will notice the movement pacing issues
my subjective opinion, which is the right opinion, is that the movement pacing issue at normal speeds is going to be a lot worse than non-alignment at normal zooms
it's not though? I'm not sure why no one is listening to the fact that rotating the world solves all of my issues with pixel alignment
I don't need help with that
i mean your background grid is anti aliased, and the pixels aren't square...
I need help finding a way to resolve workflow issues
hmm. it solves your issues with pixel alignment, but in exchange, you now have really bad movement "jitter" and "pacing" issues
I'm not asking for help with that
that are objectively a lot more noticeable
i can only help you with objectives that make sense. it doesn't make sense to gain pixel alignment in exchange for really bad movement
like i said, you cannot resolve both simultaneously with naturalistic physics
i feel like i am repeating myself. i have shipped a lot of pixel art games. i am trying to help you
including in dimetric views, using naturalistic physics
I'm sorry, but you're focusing on the wrong details that I'm asking for help with
How do I make my ship take damage from bullets but not react to the physics
well then it sounds like you've solved your problem, you have no alternative but to rotate your whole world
the shader will not help
I solved by problem, but have broken workflow
the shader will not align one art against another
I don't need a shader to align art
either make the ship not dynamic or make the bullets not solid
I'm asking for how to rotate the world in a way that does not effect game objects or scripts. Shaders can do that so that's my logical first idea but I'm not sure how to achieve that
I'm asking for how to rotate the world in a way that does not effect game objects or scripts.
i am sorry, i don't mean to waste your time. i'm not sure how to do that in a general way, and i don't think anyone else does either
there are engines that might be better suited for what you want to do, like gb studio, game maker, etc..
gb studio went very viral
wider collider around it that destroys the object and Instanciates particle on hit
there's a lot of things I can't share due to NDA, but there's a reason I have chosen the things I have done, and a lot of it involves integrating with a 3d world and 3d effects
what does solid mean
trigger / none colliding
either make it a trigger or use physics queries instead of a solid collider
maybe you'd be interested in what this guy has been up to https://www.youtube.com/channel/UCIjUIjWig0r5DIixQrt6A3A
@radiant marten he doesn't align
actualyl there's a different user who is authoring an SRP
but has no motion lol
for reasons that are clear to me
How could I run a method continuously once called, then stop running once it's over? (Eg. ChangeFov() is called, it runs until the fov is at the desired value, then stops running)
invoke repeating then break on accept
Not sure what that means
Thank you, although it needs to run with parameters
or tbh you could just use the OnValueChanged on the fov slider if it has it
use a coroutine
For example:
IEnumerator SetFov(float target) {
while (theCam.fov != target) {
theCam.fov = Mathf.MoveTowards(theCam.fov, target, speed * Time.deltaTime);
yield return null;
}
}```
or do the professional approach and put everything in an if else statement in Update ๐
Or use DOTween / any other tween library
Application.targetFrameRate doesn't seem to carry over to a windows build, is it meant to?
I could also use vsync options but I'm not sure if that can be used to get a specific target framerate
I'm looking for just a hack to mitigate wild framerate dependencies before they can be fixed properly
Application.targetFrameRate works on Windows, but it's a max framerate, it doesn't set the framerate
it also gets overridden by vSync
That could be what's stopping it in this case
perfect, thank you :)
NullReferenceException: Object reference not set to an instance of an object
EnemyMovement.Update () (at Assets/Scripts/EnemyMovement.cs:26)
I am getting this error and I think the Start() function in this subclass is causing which it, because if I remove it, it works fine, which I very much do not understand
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeapingEnemyMovement : EnemyMovement
{
public float leapForce = 20f;
public float startDelay = 1f;
public float repeatInterval = 1f;
private void Start()
{
// InvokeRepeating("Leap", startDelay, repeatInterval);
}
/*
private void Leap()
{
GetComponent<Rigidbody2D>().AddForce(relativePlayerPosition.normalized * leapForce);
}
*/
}`
also how do i format code in discord
!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.
you will also need to tell us which line is 26
wrong method of wrong script
EnemyMovement.Update () (at Assets/Scripts/EnemyMovement.cs:26)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
private Transform playerTransform;
protected Vector2 relativePlayerPosition;
protected Rigidbody2D rb;
public float moveSpeed = 20f;
// Start is called before the first frame update
void Start()
{
// Get the transform component of the player
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
// Get the rigidbody2d component of this
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
// Calculate the relative position of the player
relativePlayerPosition = playerTransform.position - transform.position;
}
private void FixedUpdate()
{
rb.AddForce(relativePlayerPosition.normalized * moveSpeed);
}
}
the content of update is line 26
playerTransform is clearly null
it's becauxse you're doing playerTransform = GameObject.FindGameObjectWithTag("Player").transform; in Start but when you add Start to the child class that means the parent Start won't run anymore
the way to fix this is to use proper C# method overriding
e.g. the parent class should do protected virtual void Start() and the child class should do cs protected override void Start() { base.Start(); // Call the base version of Start // the rest of the child class Start code }
because you skipped the first part of my recommendation
the parent class should do
protected virtual void Start()
sorry didnt see that also what is virtual
tsym
Hello, I have a question. Some players of our games reported a bug that after some time spending in our game the games stop working. We received a logs with that bug reports and we find this (screenshot). Can someone please tell me if this is memory leak or something bad?
This is in build (game is on steam). We have no clue what cause this problem ;/ any help will be very helpfull โค๏ธ
What does "stop working" mean exactly?
i would only even start worrying about memory leaking if your peak allocated memory is in the gigabyte range. youโre still at most around 270 MB
youโd need more info to diagnose
do you have a garbage collection system?
!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.
What unity version?
Anyone know , how can we write a start rotation into a Keyframe of an animation ?
can't find it on google somehow..
Im trying to get a better video.. but basically when My chicken is dropped on the floor or in KO, I want animating from current resting rotation as the starting Keyframe so it doesn't flip from a direction is not facing
My fov doesn't change even when the method is called
put Debug.Log inside while loop
loop never runs
ima take a wild guess at that sketchy != which is probably on a float
but should work ig, your condition doesn't seem it was true though
so much for
even when the method is called
lol
Debugging is your best friend
how are you calling it anyway
Alr
Here's the method that calls changefov though, everything else in it works fine
Missing StartCoroutine to start a coroutine properly
where/how would i add that
StartCoroutine(camControlScript.ChangeFov(10, 1))
Oh yep they're barely visible in light mode lol
light mode ๐ค
Perfect, thanks
also i switched to dark mode thanks for the reminder lmao
last thing, how would I make it change to the desired fov over the given amount of time
i don't want to use lerp because it never fully gets to the actual value
Look for these dots (they also appear as a white square in your vertical scroll bar on the right) often, they're analyzers that can simplify the code or fix bugs
thats because the lerp is wrong
I would do this
just replace vector3.lerp to mathf.lerp
If you're familiar with tweens you can use them too
In dotween you can use Dotween.To to interpolate between float values and use that value for whatever purpose over time
Still trying to find a fix to rotation on Animation, if any lovely knows I'd appreciate it โค๏ธ
I slowed it down frame by frame so you can see Yellow -> White
(Chicken landed on its head but when animation kicks in it flips on its belly first and finish animation after)
not familiar with those
GIYF
no wonder I wasn't finding results, I guess it's called Baking rotation into clips..
Me googling what this means is ironic
Are you looking to add a keyframe from a script?
yeah, basically if possible I want the start position of the animation to be the rotation of the "KO" pose / rotation
I was thinking of just animating it with code but had no idea how to make that flip look smooth so i just animated it
Looks like you need to use AnimationUtility and stuff
https://forum.unity.com/threads/modifying-animation-clips-through-script.460544/
Ffs, nevermind, it's editor only
dang.. I saw that one but yeah noticed editor only
idk if this helps this is my animation
so he always starts on his back belly up
which looks unnatural ofc if I drop the chicken and falls on its head for example
You could start a coroutine that lerps to a given rotation with a t value that decreases over time
public class EnemySpawner : MonoBehaviour
{
[SerializeField] List<GameObject> EnemiesToSpawn;
[SerializeField] float spawnCooldown;
TimeSpan spawnCooldownTimespan;
[SerializeField] int numSpawns;
int alreadySpawned;
int spawnInt;
void Start()
{
alreadySpawned = 0;
spawnCooldownTimespan = TimeSpan.FromSeconds(spawnCooldown);
SpawnEnemy();
}
void SpawnEnemy()
{
if(spawnInt >= EnemiesToSpawn.Count)
{
spawnInt = 0;
}
Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
if(alreadySpawned < numSpawns)
{
WaitThenSpawn(spawnCooldownTimespan);
}
alreadySpawned++;
spawnInt++;
}
public async void WaitThenSpawn(TimeSpan waitTime)
{
await UniTask.Delay(waitTime);
SpawnEnemy();
}
}
Should I be calling a wait to spawn more enemies like this? Or would you throw that into an Update loop?
haha the last 20 frames
he get chonky xD
yield return new WaitForEndOfFrame(); // ?
chiken.rotation = Quaternion.Slerp(chiken.rotation, theRotation, t);```
i'm bad at animating anway I might just try to replicate it in code but I want that same weirdness if possible lol
I'm not sure if this will work or not so do duplicate the animation first, and remove the first few frames from the animation, which you don't want to happen, then it will smoothly interpolate from your initial position to Nth frame
somehow I thought this rotation was Cool ๐ ill prob just remake it..fkit
Or you can shift the frames slightly to the right
That poor animal, probably takes a good 15 G's with that rotation
yeah good idea, Im gonna try it maybe use some Animation events
lmao and thats after he got smacked with a wooden staff
Try this first tho
will do! ty for suggestions
Select all frames and shift to right by like 15-30 frames
Might have to uncheck Write defaults on the anim state too ๐ค
basically I'm trying to mix Ape Escape with Chikens and farm lol
it just starts mid-air now
I think when animator start , it overrides transform
Maybe because of this?
Can you show your animation frames?
As long as there's nothing on early frames position and rotation shouldn't instantly snap
yea
oh wait i think its starting from here not at frame 0
Show the animation?
poor fella
i try add empty animation event to it start at 0 but still same problem
When you added the empty event, it did interpolate between initial position to 35th frame, but both positions happened to be exact same
Try to play animation again after changing its rotation to upright
wdym by this
Also poor duck training to be an astronaut with those g force levels 
Have your duck be standing normally during 0th frame, and have the animation be played "normally" from 0th frame
haha yeah gets stuck midair with the animation event in the frame 0
It should work, I don't know why your animation is starting from 35th frame tho
Ahh, welp idk then, tried toggling write default on/off?
let me try again maybe I unchecked the wrong one
yeah even with it off still weird
gonna jus try to animate it with code later instead.. animator is a pain to deal with
Ayee animation looks good ngl, except the initial fall
ty! ๐ซก
what Length is that
clip length
whats anim
thats the name of the clip
uhh this is why you show context of your code
thats 11 characters ๐
you should've specified its a string
was wondering why it was Length and not length
strings are just array, so .Length is how many items in array of char
void Swing( string anim){
animator.Play(anim);
float duration = animator.GetCurrentAnimatorStateInfo(0).length;
Debug.Log(duration);
}```
at first i did this and it didnt work so i changed the syntax i tottally forgot about it being a string
so this gives 1 which is the length of the idle clip if i call swing in a row it gives correct length
ohhh, so its working now ?
its not i just reverted it as i said it gives 1 which is the idle clip length
so what is it supposed to be ?
0.250
it works when called more than 1 time
are you sure it is in that state then when it prints 1?
animator.play is called before debug i guess it should be
do you have blend trees or any of that?
just this no parameters no layers
what are you trying to do anyway , using specific clip length iirc can vary also on fps
idk I never find using clip lengths very good
i just use Animation events
holy hell no
!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.
im trying to make swing function last for animation length
I sent the code
read this
#archived-code-general message
didnt even screenshotted it
swing function last wdym ?
you want to run the function at end of animation ?
#854851968446365696 as well, you havent actually asked a question either. I assume this is gonna be more for #๐ปโcode-beginner anyways
so there is a swing animation when it ends it goes back to idle so i need the length of the animation to invoke the function that makes it go idle
i guess i can use events or just hardcode it
Line 39 should be an error...
That startcoroutine isn't in a method
perfect code, uses .tag instead of compare tag
it technically is with that misplaced end brace
just use animation events https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
๐ why aren't errors coming up
Because technically the brace is misplaced, not missing
The end brace for take damage is after the whole die method
๐ as If ik what this means
}
This is a brace. It is the ending one
But seriously, send the code properly as said already
#archived-code-general message
There are quite a few issues with the code. It'd be nice to see all of it in a paste site
do i just put the code in there?
takes screenshot with a phone ,has andrew tate as pfp, uses skull emoji, doesnt know what a brace is
yeah im young and the problem is?
You literally have the onejoke in your pronouns but ok.
discord guidelines
thats not the only issue with my profile
Yeah, you copy the code in, hit save, copy the url, paste it here
You got a function in your function
someone who actually helps rather than making stupid unneeded comments, thank you
I can do both
and the issue is?
mate you need to learn basic c# (stop relying on gpt its only doing you harm)
Well, for one, why do you have a function in your function
That's not something you should be doing without a good reason
ive got no clue mate , i just did whatever worked
coding isn't a guessing game lol
it didnt work i guess
Also, I don't even see a question, I just see someone windmill slamming phone pictures of code with no question
alright gimmie a second lemme explain
https://www.w3schools.com/cs/index.php
Do this
Then this
https://learn.unity.com/
ohh probably coming from A*
Oh christ it's networked
im surprised you're even using A* (and networking?) when you havent done even the basics of c#
is this your project
might be the package failing to fetch updates?
Possible, maybe the package was added from a non-secure source?
If that's the case then it's probably not worth dealing with at the moment
so since adding the A* pathfinding projectmy enemy has just started dying whenevr it collides with the player. Even though the player doesnt even have a weapon yet. The enemy is supposed to just keep trying to collide with the usersprite until the health of the user sprite is 0 or the user picks up a weapon and attacks the enemy sprite so its health reaches 0 and it destroys itself.
i hope this makes sense
So what calls TakeDamage
async void SpawnEnemy()
{
EffectType effect = EffectPooling.instance.effectPools[effectType].Get();
effect.transform.position = transform.position;
effect.ClearParticlesAftertime(particleLength);
await UniTask.Delay(animationLengthTimespan);
if (spawnInt >= EnemiesToSpawn.Count)
{
spawnInt = 0;
}
Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
if(alreadySpawned < numToSpawnEnemy)
{
WaitThenSpawn(spawnCooldownTimespan);
}
alreadySpawned++;
spawnInt++;
}
public async void WaitThenSpawn(TimeSpan waitTime)
{
await UniTask.Delay(waitTime);
SpawnEnemy();
}
is there a way to interupt the "WaitThenSpawn" so if all enemies are dead)found with a isEnemies bool it stops the delay and immediately called SpawnEnemy
cancellationtoken i think
when the enemy sprite collides with the user sprite or the User sprites weapon makes contact with the enemy
sweet thanks...chatgpt apparently know all about those
will see if its horrible wrong ๐
thats probably better ๐
wonder if I should just not use the UniTask
So, the TakeDamage function is the thing that kills the enemy.
TakeDamage is called when the enemy collides with the player.
Your enemy is dying when it collides with the player.
And this is apparently not expected behavior?
and use a different way to do it so I dont need to do cancellation tokens
I just never used UniTask so not sure if that affects it
Unity has their own version of it basically
Im thinking maybe just an old timer that checks each time in update might be better
https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.html
ah yea this is only 2023 apparently..
i think im just explaining it wrong, hold up
@naive swallow does this help?
No? What does this have to do with the code you posted before?
this is how I should just do a basic timer right?
float elapsedTime=0;
public void Update()
{
elapsedTime += Time.deltaTime;
if(elapsedTime >=spawnCooldownSeconds || GameManager.instance.EnemyList.Count == 0)
{
SpawnEnemy();
elapsedTime = 0;
}
}```
or should I be storing initial time, and current time and doing math based on spawnCooldownSeconds
elapsedTime -= spawnCooldownSeconds; will be more consistent but yea thats fine. Some people like to use the current Time.time then check when the next spawn time should be, but its the same outcome
TakeDamage is a function that basically takes away a certain amount of helath from the player or enemy
I dont follow the "more consistent one"
Right, and where are you calling it
how would that be more consistent?
isn't that just
elapsedTime = elapsedTime - spawnCoolDownSeconds which would be doing math each time it checked that?
sorry i meant instead of elapsedTime = 0;.
If elapsed time becomes 2.01 and spawnCooldownSeconds is 2, then you now "lose" out on 0.01 seconds of accuracy. A bigger example would be if your game froze for 4 seconds, elapsedTime is now 4 but is set to 0 instead of spawning 2 enemies back to back
these are all the places i call it
oh awesome thanks ๐
hadn't thought about that!
thats for a weapon
Yes, which is destroying every enemy it touches immediately
but at the start of the game the user doessnt pick up any weapons yet
void Start()
{
//disable the sprite
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.enabled = false;
GameManager.instance.EnemySpawnerList.Add(this);
alreadySpawned = 0;
animationLengthTimespan = TimeSpan.FromSeconds(animationLength);
particleLength = TimeSpan.FromSeconds(animationLength + 0.5);
first = false;
spawning = false;
elapsedTime = 0;
}
public void Update()
{
if(alreadySpawned>=numToSpawnEnemy)
{
Destroy(gameObject);
}
elapsedTime += Time.deltaTime;
if(!spawning && (elapsedTime >= spawnCooldownSeconds || GameManager.instance.EnemyList.Count == 0))
{
SpawnEnemy();
elapsedTime = 0;
}
}
async void SpawnEnemy()
{
spawning = true;
//do animation
EffectType effect = EffectPooling.instance.effectPools[effectType].Get();
effect.transform.position = transform.position;
effect.ClearParticlesAftertime(particleLength);
//spawn enemy after delay
await UniTask.Delay(animationLengthTimespan);
if (spawnInt >= EnemiesToSpawn.Count)
{
spawnInt = 0;
}
Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
alreadySpawned++;
spawnInt++;
spawning = false;
}
When the first enemy is spawning
a second one immediately spawns after
and I can't figure out why that is
adding spawning bool which should prevent that?
Add this to the enemy script:
void OnDestroy(){
Debug.Log($"{gameObject.name} has been destroyed");
}
and then show the stack trace of this in the console
is there a reason you're doing async instead of just using Coroutines ?
just not a fan of how I have to call Coroutines so async just feels better ๐
I could see how that might break it though thanks
alright
@naive swallow
Now show the stack trace
does making a method virtual make it take longer to run in any way?
probably slower on the compile but otherwise doubtful
sorry but what does this mean?
The stack trace, when you click on a message in the console
that shows where it was called from
do you know what a stack trace is?
isnt it like a report?
It's the bottom half of the console window
when you click on any console message
It's a bunch of lines that tell you where, and what exactly was executing at the time the exception/log was printed
Super useful stuff
ex) click the error, CTRL+C and then it will print like this
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <f94752164e14499c83c250d9839d9e96>:0)
Okay, now show it for the log I said to use
Hm, so it's not saying what's calling the Destroy
wish i could programme using pseudocode
Well, let's see if it's TakeDamage that's doing it. Add this line to the top of TakeDamage:
Debug.Log($"{gameObject.name} is taking damage");
and see if it logs right before this destroyed line
This seems to be unrelated. If the log is inside TakeDamage, then that's not the thing that's destroying it

btw where did you get the A* from , did you get some outdated package or something lol
Now, put another log inside of MeleeAttack:
if (collision.gameObject.CompareTag("Enemy")) {
Debug.Log($"{collision.gameObject.name} is being destroyed");
Destroy(collision.gameObject); // Destroy the enemy
Keep the other log there too
Did you just paste my half-a-function into somewhere in the script? Only the log should be added
the rest of it is showing you where to add it
lmao my bad
ive got a problem in my game, where im trying to use a box collider to start an animation on collision through script, but hes starting his animation as soon as i start running the game
is it a problem with the code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimTrigger : MonoBehaviour
{
[SerializeField] public GameObject player;
[SerializeField] private Animator anim;
void OnTriggerEnter(Collider col)
{
if (col.gameObject == player)
anim.Play("LiamWalk");
}
}```
yeah none of the characters are moving now , idk y
Put a log in the function and see if it's called when the game starts
how
Debug Log should literally have been the first line of code you ever wrote
@naive swallow any clue why its doing this now?
did you actually start the game
yep
Did you change anything other than putting in the log
and did you fix whatever you did that broke compilation the first time
You now have an index out of range error
errors keep coming from random places
That tends to happen when ChatGPT code is slapped together with wanton disregard for code structure
i only use chatgpt if there is a error i can figure out on my own
Got no other resources so chatgpt is my last and only place
Clear errors, run it again, see if it actually runs
bro i dont remember how to do this anymore
its been so long
thank you
so you didn't even try to look it up
It's literally the first result for "debug log"
It's the first result for that too
i looked "how to write debug log in c#"
Second result
Then this code is not playing the animation
i removed the "animator" component (which was causing it to go immediatley), but now it just doesnt go when i trigger it
You write:
Run() { MoveCharacter(); }
MoveCharacter() { rigidbody.MovePosition(nextPos); }
The way the program executes is: it tries to call Run(). In the middle of calling Run, it needs to call MoveCharacter(), so it freezes time right now, and opens a new level of the program. In this lower level of the program, it is going to go do whatever you do in MoveCharacter(). Then it reaches MovePosition, so it freezes everything in place again. Then we make ANOTHER level of the program, were we are doing MovePosition.
These are called stack frames.
Every "level" is a stack frame. A stack trace is printing everything we have on the stack right now.
If you are in the middle of executing MoveCharacter, the stack currently looks like
1 - MoveCharacter()
0 - Run()
If you are in the middle of executing MovePosition, the stack currently looks like
2 - MovePosition()
1 - MoveCharacter()
0 - Run()
Understand?
Kinda
Alright
it's known as THE stack
A stack is a type of data structure. THE stack is A stack that is used for THE execution of the program.
Also any advice on how to get really good at programming in a 6 month period (specifically Pseudocode and Python?)
take a class
go to school
get an education
that's literally the reason schools exist
it's very easy to teach yourself to program like shit. Only a teacher can teach you how to program properly
So basically I've got my exams in like 6 months and one of the papers requires a decent amount of coding, ik Abit of python and I've just recently started using unity with C# , Should I stick to Python or try convert to C#?
๐ญ My teacher can barely code lol
I just recently started doing the 16hr free Harvard course on YouTube
If your teacher is only asking you to code.
Cause I take computer science, idk why he can barely code doesn't make sense
I'd suggest making a discord bot on python.
Or something you can readily demonstrate.
Surely you'd need a fair bit of experience for a project like that
that is some bullshit. even my chemistry professors, when they asked for code, it was always something they and all the TAs could do with ease
You don't have to bend over to learn C#, if you already know python it should be able to get faster.
Some kids in my class teach him๐ญ
You'd need even more with C#.
Even more with Unity C# since they break some conventions.
my man doesn't know about the stack. He needs more than a little bit of help.
Yeah that's why python is probably the easier way to go.
that doesn't address the core issue
We have to make a project, I chose a game, so it was either pycharm, unity or defold or unreal, and I chose unity
if this is a programming class, then it is expected that your teacher is a master
I thought u meant stack as in data structures ๐
For a college school, it's an embarrassment to have a teacher to not even know programming on a programming class.
the stack is a stack, but not every stack is the stack
anyway, you need to strike at the core issue: complain, or swap classes. This sounds like a shit class
๐ญ ig in the UK it's different, I'd say about like 2 guys in my class are far better than the teacher at programming
No other class to swap to
My chem teacher is electrical, but even he knows chem.
my physical chemistry professors all had coding projects, which they could do like the back of their hand
no excuse
@broken zodiac If your deadline is like a month, you don't really have a lot of time to make a sizable game.
I'd probably think of a dyno or flappy bird clone which is easy to do in a day.
you chose something very hard (relatively) then since this clearly isnt a c# class. Is this a university class if you dont mind answering? You should really make something simply like even html and javascript. I doubt these guys are expecting work that requires a full game engine
And those games don't need unity at all.
Nah I'm not at uni lol, highschool
I figured as much based on what you were saying
anyway, back to this channel's original purpose:
I have my own infinite stack trace problem:
Stack overflow: IP: 0x159c00edd, fault addr: 0x7ffee7629ff8
Stacktrace:
at <unknown> <0xffffffff>
at ForestGraph1<TStored_REF>.SortTree (System.Comparison1<TStored_REF>) [0x00000] in <...>
This happens when I call this public method:
Comparison<TreeNode> nodeCompare = new Comparison<TreeNode>((TreeNode x, TreeNode y) => compare(x.self, y.self));
SortTree(compare);
}
protected virtual void SortTree(Comparison<TreeNode> nodeCompare) {
rootNodes.Sort(nodeCompare);
foreach (TreeNode node in EnumerateBackwardsGraph())
node.children.Sort(nodeCompare);
}```
Before I had:
```public void SortTree(Comparison<TStored> compare) {
Comparison<TreeNode> nodeCompare = new Comparison<TreeNode>((TreeNode x, TreeNode y) => compare(x.self, y.self));
rootNodes.Sort(nodeCompare);
foreach (TreeNode node in EnumerateBackwardsGraph())
node.children.Sort(nodeCompare);
}```
and the same exact call was working fine. Any idea why I'm currently getting a stack overflow?
Ok, high school is definitely a different standard.
your teacher might've never learned to code in the first place, i wouldnt blame them. they're just filling the position but its a shitty situation. If you can, swap to something easier. If you do want to do unity game dev in the future, then consider continuing with this project but really make it simple. You're trying to learn c# and unity at the same time, its a lot harder than learning unity while already knowing c#
So far I've created a top down game, which a
Has a character that can pick up different weapons and attack different enemies, also has a timer that stops when the users health reaches 0, I've also made a minimap at the top right of the game and added like pause/start /end screens
high school is different. high school teachers are underpaid, and not like the top of their discipline. no offense to high school teachers
He's a computer science teacher so idk why he can't code that well
He was probably put into that position.
college professors literally do research. they have to be at the cutting edge just to do their base job properly. And then they teach as a side responsibility
sometimes you get instructors being brought in, but a real good school should have most of your professors being actually accomplished researchers.
could that SortTree(compare); call be calling itself?
This sounds manageable, even in none unity.
If you don't use unity here, I'd suggest making collisions out of circles.
Which is only determined by distance of object a to object b.
I think I already do that
oh god you're right, lmao
Very simplified but suffice for a supposedly simple game.
I thought I was calling the protected virtual method because type, but I wasn't
ty bawsi
I'm just going to get good at Pseudocode and smash the CS exam in 6 months, then off to uni to study Finance and mathematics ๐
U have 6 months before deadline?
Nah deadline for the project is in a month, but we have a coding paper in 6months
Ah.
you don't get good at pseudocode lmao
you get good at regular coding, and then express yourself to real people using pseudocode
If ur good at lua/ python you'll be good at Pseudocode
sir, you are extremely confused
I disagree
pseudocode isn't like a real skill that you hone
pseudocode is just a way to talk about a program
which doesn't work if you don't know shit about programming
It is very similar to lua and Python
no.
pseudocode is not a programming language
pseudocode is what math professors use when they are forced to teach a computer alg class
Well ig the whole UK education system is wrong cause it starts that in our syllabus
you see a lot more pseudocode in theoretical computer science, where the program and machine are both theoretical
Anyways, here's a quick way to do this for the combat side of things.
- Bullets don't have collision.
- Characters get hit when a bullet is close enough to them. (Use a distance calculator)
- New bullets should add to a global list of bullets. (Which are then used by all characters to check if all bullets are close enough to them)
- Bullets that hit immediately get removed on the game. Don't add piercing mechanics, if you add piercing mechanics, it will just complicate it.
This should allow you to make that game even if it's not Unity under month.
Hey how can I stop the console editor from stacking same debug statements on top of each other?
I forgot to say I've already added a projectile launcher that destroys itself aswell as the enemy when contact is made
o ty hehe
if this is for a class, you should focus on learning the fundamentals of programming
jumping straight into programming without knowing anything is just going to be a trainwreck
especially if your teacher is incapable of teaching you proper style, proper documentation, self-documenting code, etc etc
these are important skills that you don't normally learn from a random youtube video. these are things you learn in school
Just learnt what that was last week ๐ญ
I can't learn them at school so that's why I come on servers like these to ask you guys
In this Harvard course I trust
just for reference
this is what garbage tier code looks like:
var r = ((int)o << rb[(int)b])
+ ((int)o >> (4 - rb[(int)b]));
r = r & 0b_1111;
if (b >= 4) {
r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);
}
return (Cardinal) r;
}```
same code but in proper style:
public static Cardinal RotateCardinal(Cardinal original, Rotation rotateBy) {
Debug.Assert((int)original >= 0, "Tried to rotate a NEGATIVE cardinal value! Cardinals should be 0-15!");
Debug.Assert((int)original < 16,"Tried to rotate a cardinal that was >15! 15 is the max for having the total # of directions!");
// Bitshift to represent rotation. Moves all 4 cardinals into right spot in flags
int rotated = ((int)original << rotationBit[(int)rotateBy])
+ ((int)original >> (4 - rotationBit[(int)rotateBy]));
// Now the main 4 bits are right. Get rid of out-of-range bits.
rotated = rotated & 0b_1111;
// More bitmath. That operation above rotates by 2, so L/R are flipped. now isolate U/D and add back in
if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);
}
return (Cardinal) rotated;
}```
this is the sort of thing you need to learn
style
๐ I'm so thankful I chose not to do computer science at university it looks terrible
good style allows you to actually know wtf it does
I just fill my code with comments
like how would you know wtf this does: if (b >= 4) { r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);}
comments are just one tool. a tool you need to use the right amount
manipulate the variable 'r' based on the condition that 'b' is greater than or equal to 4. It uses bitwise operations to modify 'r' by shifting its bits and performing bitwise AND and additional operations with specific bitmasks.
ok. what does it actually do
Ah I see
you told me what the math says it's going to do
but you did not explain what it is doing, and why it is there
if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);}```
Oh look, an actual explanation
if (b >= 4) { r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);}
The purpose of this code could be to alter certain bit patterns within 'r' depending on the condition, possibly for specific bit-level operations or optimizations within the program.
this whole function takes in cardinal input, which is a combination of bits in an integer corresponding to up-down-left-right.
the function tries to rotate this cardinal
that line checks if the rotation (an enum type) is set to flag for a mirror plane
then the actual bitmath applies a mirror plane to flip
๐ฅฑ good night speak some more tomorrow
point being, learn style. good night
Good and organised code with properly named methods, and variables > comments

I'm having some issues with script inheritance.
{
GameObject projectileGO = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);
TrackingBulletBehavior projectile = projectileGO.GetComponent<TrackingBulletBehavior>();
if (projectile != null)
projectile.Seek(target.transform);
}
I'm using this function to fire a projectile from a tower, but I'm trying to generalize it so that the tower can instantiate any type of bullet and still get ahold of its script component.
my bullet scripts extend off each other like this
is there a question there?
But I'm trying to search for any "ProjectileBehavior" and just use the overwritten "Seek" function
yeah
its not inheriting
and im not sure why
I changed it to ``` void Shoot()
{
GameObject projectileGO = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);
ProjectileBehavior projectile = projectileGO.GetComponent<ProjectileBehavior>();
if (projectile != null)
projectile.Seek(target.transform);
}```
and it doesn't compile
cant you just spawn is as ProjectileBehavior
show the whole script using a paste site:
!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.
but I can see you are not using override, so that may be the issue? Can't tell without seeing more
also what is the error
Or just show the error
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
And what script contains Seek?
btw OnDisable is not capitalized properly
ah ty
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
That is a child
the parent won't have it
correct
So why do you think it would work? The parent won't know what the child has
If seek was in the PARENT of BulletBehaviour, it would work
Not the other way around
I'm trying to search for any script in the game object that is of the type "ProjectileBehavior" and since all the other scritps inherit from it all the way at the top
btw
public class something : MonoBehaviour
{
A a;
private void Start()
{
C instance = Instantiate(a) as C;
instance.Cheese();
}
}
public class A : MonoBehaviour { }
public class B : A { }
public class C : B { public void Cheese() { } }```
Ok, that is fine. You just need to figure out what the child has and cast to that
You could, for example, have an enum in ProjectileBehaviour that is the type. Or you can use Reflection I guess
reflection?
huh?
skip the get component, spawn it as whatev you want directly
you lost me, why would I need to cast anything
Because TowerBehaviour BulletBehaviour does not have Seek
that's the issue. I'm trying to generalize it in the method that way it will work with any projectile prefab I drop into the tower
did you see my example
thats casting
Sorry, I mean BulletBehaviour
You need to cast it to TrackingBulletBehaviour, which DOES have Seek
Seek is ONLY known by TrackingBulletBehaviour and any class that inherits FROM it. No parents know about it. So cast to TrackingBulletBehaviour or a child.
That is all
just making sure I understand, my code currently is grabbing the TrackingBulletBehavior but it's treating it as just a ProjectileBehavior, right?
Yes
I understand the part you guys are explaining
It is treating it as exactly what you call it
gotcha
so it's got the right script, I just have to specify by casting so it knows to look for Seek()
change ur prefab type first
but then wouldn't I have to hardcode that in for any projectile that does or doesn't use that method?
public GameObject projectilePrefab; should be ProjectileBehavior no?
im aware
I would say yes. You can always do .gameObject from the script reference. But you have to do GetComponent going the other way
what is the point of this inheretence then ?
ProjectileBehavior would mean you can put any of the child classes you shown
then how would the tower store a reference to the prefab that it instantiates?
setting up skeleton for different projectile types/behaviors
but I plan to cut down on it because there is too many layers as is
right so you want to just have them as ProjectileBehavior not GameObject
almost never a need for GameObject instead of the actual type you need
public ProjectileBehaviour prefab
ProjectileBehaviour newProjectile = Instantiate(prefab);
That will spawn the whole gameobject with all other components and values
You almost NEVER need a gameobject reference
If I Instantiate UI objects in a particular parent, is it's SiblingIndex able to be pre-determined? Should it always be the highest?
I feel like it should always be the lowest
But I dunno. I would guess it'd either be lowest or random, but not highest. Just guessing though
what do you need to do that you are messing with indexes?
got some bugs with me cards ordering, like when I draw a card, I instantiate it into my hand.
but it appears that the siblingIndex it's instantiated with is random ...
make a field called newestDrawnCard or something and pass that?
Draw, store it, pass that
ahh is it cuz prefabs are all inherently GameObjects?
they turn into whatever you spawn them as
GameObject creates the instance of your scripts sitting on it
huh
its like a container ig
all monobehaviours sit on a gameobject
wdym by sit on
idk like exist on?
as in a component?
sure all scripts on gameobjects are components
any monobehaviours can do .gameObject inside the script and its property in the monobehaviour class
of the object that contains that component
basically was saying just do ProjectileBehavior projectile = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);
but you have to change projectilePrefab from GameObject
ohhhhhh
since you're trying to spawn it as ProjectileBehavior
otherwise you get type mistmatch error
so when I do instantiate like that, then is projectile a direct reference to the script?
projectile will be the instance of that script
yes sorry, I meant the script on that instance of the prefab
the prefab will turn into that yes
gotcha, thanks
now it gets mad if I try to cast
show current code
what type is projectilePrefab
My bad. I forgot to desc this. The game loses whole input. I mean whatever player Press it does nothing. The game its not freeze (there are sounds, animations of Birds).
There is one moment in game where they are stuck in this but we tested it and everything is fine. Zero errors or nulls in logs. Its appear when they play for a couple of hours.
{
ProjectileBehavior projectile = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform) as ProjectileBehavior;
if (projectile != null)
projectile.Seek(target.transform);
}```
yeah projectilePrefab what type is it
ah
2022.3.10
And we use hdrp
might need to drag prefab back in after that
Not sure. How I can check this?
C# is garbage collected, so not sure what they mean with that
we memory manage now
yup, got it back
just gonna shift stuff around and fit it into the project
tysm
if you're using unmanaged arrays and stuff like that if you don't dispose then you can leak
or w/e I've just been using them and blew up unity a few times
Does anyone have any experience with hand tracking with MediaPipe? I'm using it for a project and I'm having trouble implementing both hands.
sounds like a problem with input handling or UI event handling then, not a memory issue.
did you configure it to track more than 1 hand
how can i change an int's value with a slider im trying to make a volume thing
you can set your slider to whole numbers, but since slider really only deals with floats you'd have to get its value then cast or round it to an int.
however if this is for volume you'd be better off making your slider go from 0.0001 to 1 and just display it formatted as a percent. Then you can just use Mathf.Log10(sliderValue) * 20 to get the value in decibels for your audio mixer
ok thanks
- I'm doing a bottleneck optimization here. The game creates around 2-4k objects, each of which fetches components in their hierarchy and sorts them. This is the second most time consuming operation done by these objects. Hence, there are several questions of mine:
- My tests seem to confirm that the order of the returned array is always identical. However i'm told not to rely on this. Is there any reason not to? I could cut the sorting time 10 times already if i cached the permutations after performing a sort on the prefabs.
- Not really scripting, but if the 1st point is valid and i should not expect to get the same order in get components method result, how much of an impact will de/serializing references to the components be? Is it any faster than fetching components in children?
- And lastly, if both previous point fails, is there any internal magic that enhances the execution time of the built-in method that i could not achieve while making my own version of it?
yep, why dont just serialize the reference to prevent 2-4K calls to getcomponent after you spawn it, btw i have no idea what you means by "sorting the components"?
i remember the return order is based on the scene tree, if you dont modify the scene that you can rely on the order, but it is impossible for you not to modify the scene
- Sorting is a game-specific thing. The bigger index is, the higher the object must be, hence the objects are sorted by their height. And yes, it happens in every f*cking single objects that gets spawned. Idk either what was the guy who made this thing high on
- Also, re: scene tree. Does it include instantiating objects at runtime, or just moving things around in the editor?
oh, sorting when a new object spawned?????
you just need a sorted set (red-black tree ) or skip-list to maintain a sorted order
insert and remove takes O(log n), pretty fast
i think you should talk it to your partners or whoever, to change the data structure
- Well, it happens on every spawned object now, but i'd very much like to avoid this nonsense. All it does is repeats the same sorting task thousands of times. I seek to cache it, or at least rework it so doesn't have to happen to each object individually
I'm trying to pause my game with timescale but for some reason my event triggers im using for my UI arent working
How are you using your event triggers? And how are you confirming they are "not working"?
But only after 3-4 hours of playing?
Im trying to use CreateAssetMenu and ScriptableObjects for a making cards for a card game. Is there any way with the asset menu to make something like "if the (damage card) boolean check box is clicked show the make a damage card menu" within the asset creation menu. (sry if this is explained poorly)
- Conditional context menus are not a thing unless you find something related in the asset store. You're better off creating your own editor window at this point
Heya - Working with Unity's ECS, and having some extremely weird problems with empty components.
When I apply a large number of empty components to entities all the other systems seem to act in a bizzare way as if there is a memory leak although there is no leak?
I'm declaring the component as follows. When using the component like this it's causing the above issue.
public struct CCompletedIntercept : IComponentData { }
When declaring the component with a dummy field the above issue is gone?
public struct CCompletedIntercept : IComponentData
{
public bool dummy;
}
Hi, does anyone know how to replicate this type of thing in a custom script?
Think this is more relevant for #1062393052863414313
That is a unity event
Ah, perfect! Thanks! Another quick question if you don't mind. While I was searching on how to replicate this I tried digging inside the Button.cs script but couldn't find the member variables such as the UnityEvent or any of the colors for button interactions, bools, etc... that we can see in the editor inside a button. Is there a way to find these by chance so that next time I can analyze how something is done without having to ask questions?
Hello! I want to implement this reward system on my app, but I'm using firebase authentication with login and registration, if I follow this, will this still be save on the user's account? or should I incorporate firebase to the reward system? I'm planning to just follow the tutorial ๐
In this video, I'm going to show you how to create a simple reward system for your hyper or hybrid casual game, you might be wondering what the benefits of adding the reward system are in summary, this feature will increase engagement and the chance of players watching rewarded ads. Ok, let's get to it
State.io Clone tutorial:
https://www.youtu...
Not on my pc so I cant really check what I'd see if I f12'd on Button. Maybe some of it is from the custom editor layout
I see, would you perhaps know how to access/find a custom editor layout for specific unity components?
๐คทโโ๏ธ not really sure what you'd want to see from it, although maybe you can see whatever you're looking for online. Usually it should be enough to just go through the docs since itll describe what most fields are
Alright, thanks for all the help! I really appreciate it!
when i pull up my pause menu i am setting timescale to 0 at the same time, but when i try to click on my UI or use a controller to navigate it nothing happens
So this is not 100% related to coding but what I have is one main camera rendering everything except the hands and the gun and one camera that renders the hands and the gun (btw forgot to say I am making fps) so the problem is I am making a bullet line but it comes from the gun tip but the weapon camera fov is different and it is causing it to be shifted to the left .What should I do ?
AFAIK, animations on the UI might depend on time scale being above 0 (if they are not set to "unscaled time" for their animator components), for interactions though, are you sure there is no other UI elements blocking your buttons? Do you have a event system in your scene that is enabled and setup for the input system you are using? Are you using a Canvas Group on any of your UI/canvas? Do you have "raycast target" turned OFF for those buttons? If so, you may want them ON, these things may typically prevent mouse events like clicking, if you havnt already checked all of them
I don't really know if there's a great solution for that.
All I can think of is doing some math to offset the bullet (preferably its visuals only) so that it matches the FPS camera, then fade away the offset as the bullet flies away
Idk if this makes it any clearer, but here's a sketch.
It's top view. White lines are the camera direction/frustum, red is the gun, blue is the projectile
Yellow is just the center of the view
the menu worked fine before i changed the timescale so im assuming it just doesnt work well with timescale being 0
Its possible, though that would seem odd to me that timescale would affect click events, since that doesnt really depend on "time"
I just tested in a project that also uses Time.timescale for a pause menu, and doesnt seem to affect interacting with UI elements like buttons, you could try moving your UI to an isolated scene and have a script toggle timescale to test
serialized unity array looks like this for some reason
the variable in code
[SerializeField] private int[] bonesToWalk;
Type in 1
Do you have a custom editor for that script?
nope
Assets\HumanAI2.cs(38,33): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
there was an error after I typed in 1
Oh I mean type 1 in the inspector, where it says 0
thats an entirely different variable
Ah damn, I thought that's the array size field
It should just show like this
Do you have compiler errors?
And what kind of object is this on? Maybe the share rest of the code
Because the line you shared is correct
Resetting the editor layout could help, if it's some GUI bug
I've completely restarted the project, there are no compiler errors.
That doesn't reset the layout. But other than that, no idea
didn't fix it
What if you initialize the array, does that change anything?
Next thing I would try is changing the array's name completely and see if it helps
wierd thing is that there are other unity arrays in my scripts above this one that work but all the ones below dont
nope
Below what?
What else are you drawing in between? Like what fields
that array in my variable declaration
wait, no, thats not it
WTF
every unity array I close turns into this
๐ค What unity version?
Yeah definitely a bug
this is an entirely a new script
You aren't using Odin or other custom inspector stuff, right?
Update Unity, that's an old version
Is your inspector in debug mode?
idk if im just being pepega, but for some reason, this code (which is in update) keeps randomly forcing the rotation of the camera to be forward center as long as the targetRotation is 0,0,0. And I mean instantly, hard setting it and cause the camera to stutter. i dont get why this happens. the vid i stole this from has only this code and it work perfectly and it does work perfectly as long as targetRotation > Vector3.zero.
both of these should result in the same thing right as classes are copied by reference or i'm i worng
Vector3.Lerp is not really meant for euler angles
Neither is Slerp
This would be more appropriate Quaternion.Slerp(Quaternion.Euler(someEuler), Quaternion.Euler(anotherEuler), speed)
Or Quaternion.identity instead of the Vector3.zero
Another option is to use Mathf.LerpAngle for x, y, and z
that did not fix the issue
this still causes the stutters i mentioned. not sure if i did it wrong
You are still using Vector3.Lerp for a rotation
I'm not even sure if I understand your problem fully - that's just what stuck out for me
Good god, I didn't even think is was legal to name your variable var. You really shouldn't
Anyway it's unclear what you're asking. Is NoiseSettings a class or a struct? Are the two noise settings variables the same?
well the targetRotation is what the recoil amount gets plugged into. my issue is that if targetRotation is greater than 0, than it causes my camera to stutter and try to force itself to look center screen on only the x. i dont get what it's happening
Thx for the answer I will try that I have another idea on my mind though just to move the weapon camera
actually, i think i found the conflicting code and now i just go to figure out how to get them both to work.
@hexed pecan yoo I got another idea just to render the line only using the weapon camera but won't this make it on top of everything
Yeah, that's problematic
Yea
Bro such a simple thing but of course it's going to be the hardest thing on earth
You have a fixedDeltaTime here ๐ค Does this run in Update?
Dual cameras are tricky. I gave up on them when I realized that objects from the main camera can't cast shadows on the gun/arms camera...
I chose to implement weapon collisions instead
I prefer that anyway
Bit less artistic freedom since you can't adjust FOV separately, but a lot of problems gone too
yeah the no shadows on fps weapon is a real turn off from camera stack
I think Tarkov managed to do it somehow
Like the weapon FOV doesn't change if you change your FOV
But their render pipeline is probably very customized
I duplicated every object I want shadows and just made it only render shadows
Oh yeah, that's the one solution to it. Just not very scalable at all, at least for my purposes
Yea If I have 1000+ objects it's not very good
Ok then what should I use
For the hands and weapon
As I said I personally chose to use a single camera. So I can't recommend anything else
And fixed weapon clipping to walls with a basic weapon collision system
Can't I just use render texture and swap ui raw image on top
To solve what exactly?
I don't know anymore
These cameras are shit
For example how valorant did this
Or CSGO
Maybe some shader magic. Different projection matrix for the gun/arms or something...
Not sure though
hello everyone, i developing a 2d game. I have TMP_InputField in my scene's middle. after that, i touched inputfield in mobile (iOS or android), the keyboard takes up almost half the screen. how can i solve this?
it was, but ive moved it to lateupdate
Ok, use deltaTime
fixedDeltaTime is for FixedUpdate
And again, Vector3.Lerp is not for eulers
I can see the arrays if I open the script up as properties and enable debug mode in the property tab. It works but I hate it
you can use [field: SerializeField]
is array of custom class?
?
i figured out my issue and it isnt the vector3 vs lerp thing. the vector3 is using measurements i made for recoil so it has to stay as a vector3. my issue is i have 2 things setting localRotation at once and im not sure how to add them together
its on every single script
Okay, in that case Vector3.Lerp can work if you use your own values and it doesn't have to loop around 360
To answer the question: you can multiply to quaternions to "add" them together
The left-right order of the multiplication might matter, try both ways
i see. my other code that is interfering is my mouse movement code which is on lateupdate while my recoil code is on update. how do you suggest i make the movement code check for current recoil?
Try changing the = on that line to *=
i did and it makes my screen go crazy when i move my mouse
Ok sorry can't read all the code right now, a bit busy
nah man. you're good
i'll wait however long i need to get help
it is the default unity starter assets code
thought you said you array wasnt showing up inside inspector
i was asking if it was an array of a custom class
good ol GUID +Dictionary
forgot the full details i used for this but it was a pain but easy enough
When I get home I will try moving the camera if the result is decent I will use it if not I will offset the bullet line
is there a way to simplify this?
if(target.transform.position.y > transform.position.y)
{
if(target.transform.position.x > transform.position.x)
{
curveCounterClockwise = true;
}
else
{
curveCounterClockwise = false;
}
}
else
{
if (target.transform.position.x > transform.position.x)
{
curveCounterClockwise = false;
}
else
{
curveCounterClockwise = true;
}
}
This I think?
Vector2 myPos = transform.position;
Vector2 targetPos = target.transform.position;
bool above = targetPos.y > myPos.y;
bool right = targetPos.x > myPos.x;
return above == right;```
i mega minded it and got it fixed. i just added an extra game object to my character and had recoil hit 1 game object and mvoement hit another and then get the camera to follow the higher one. thx for trying though. i appreciate it greatly
y> and x> = true
y> and x< = false
y< and x> = false
y< and x< = true
yeah looks like that works thanks!
this feels wacky to do lol
curveCounterClockwise = (above == right);```
usually youโd want to define these sorts of things based on angles, or implicitly with dot products.
this logic is simple, but it depends on the specific use case if it is good enough
If I wanted to put in some demo functionality that wouldn't normally run unless I'm in a debug type mode, but I wanted to consolidate the definitions of the demo mode functionality to an interface, how savage is it to put an #if TESTMODE interface like this?
public class BaseGame
#if TESTMODE
: DemoTester
#endif
{
}```
Does someone know how I would implement a tilemap which the player can use to interact and build stuff.
The fov never resets or even lowers, however it says that ResetFov runs, once, at the correct time.
cannot start a coroutine like that
I am so stupid ty
Ok, well now it keeps increasing the fov
to start with, never check floats for equality
How would i go about making it so that my 3rd person player cant move outside the vision of my static camera so i.e moving my player left off screen will just mean my player doesnt move almost like a collider
You can take the position the player will be moving to and convert it to viewport space
https://docs.unity3d.com/ScriptReference/Camera.WorldToViewportPoint.html
From there, you can see if that position would be beyond the bounds of the view if either x or y are less than 0 or above 1.
When the player is hit by the bullet he get a knockback but only in y axis the x remain constant even though i didnt lock x in the rigidbody of the player
public class Player_Life : MonoBehaviour
{
[SerializeField] private float health = 10;
[SerializeField] private float startLavaTimer = 0f;
private float lavaTimer;
private bool insideLava = false;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
lavaTimer = startLavaTimer;
}
void Update()
{
CheckIfInLava();
}
void CheckIfInLava()
{
Debug.Log(health);
if (insideLava)
{
lavaTimer -= Time.deltaTime;
if (lavaTimer <= 0)
{
health--;
if (health <= 0)
{
Destroy(gameObject);
}
lavaTimer = startLavaTimer;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("Lava"))
{
insideLava = true;
}
if(collision.gameObject.CompareTag("Bullet"))
{
rb.velocity = new Vector2(5,2);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
insideLava = false;
}
are you overriding velocity somewhere else?
this is my player movement
public class Player_Movements : MonoBehaviour
{
[SerializeField] private float speed = 0f;
private float horizontal;
private Rigidbody2D rb;
public Transform groundCheck;
private bool isGrounded;
[SerializeField] private float jumpForce;
public LayerMask whatIsGrounded;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, whatIsGrounded);
if(isGrounded)
{
if(Input.GetButtonDown("Jump"))
{
rb.velocity = Vector2.up * jumpForce;
}
}
}
}
well there you go
rb.velocity = new Vector2(horizontal * speed,
you'd have to put some sort of bool probably
I prefefer simple FSM
even when i am not moving the x does not change
you're still overriding it
with 0
speed can be 1000
if horizontal is 0
it will be 0
you need to do rb.velocity.x in there when KNocked back
Hey I am trying to do a game project for school and I want to know if I can have a code editor within a game to allow people to code in the game.
And will I be able to do it and post it on webgl
Why my pause dont work? It worked 5 minutes ago
Yes it's possible but it's difficult to do safely especially if you're an amateur programmer.
You'd have to choose which scripting language you want the user to use and go from there, but typically it means running a scripting runtime within your game
You'd have to show how the movement code works
Presumably it's ignoring time scale
Everythibg worked perfectly fine 5 minutes ago, now i reopened the project and everything broke
Irrelevant
Need this to answer the question
This project is like 7mknths old and im trying to improve it
Ok
I mean I do have some experience but I've never done something like this before. And it being c++, would that make it hard. Its also a could have festure
You want the user to write C++?
Yes that would be very hard
And unsafe
How so?
C++ is a language that allows the user to directly access and modify arbitrary memory locations.
Not even C# does that really
It's also a compiled language
It would be very complex and ill advised to use C++
Something like Lua or JavaScript would be more typical and easier to control
@hexed pecan just did the offset thing and it works like a champ thx for the idea
๐ 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.
I cant post ss rn
Then come back later, most of these are blurry or overexposed, too hard to read
I cant open discord on my pc
๐ญ
No one wants to help me
Once you will post code properly, this will change
Thanks I'll keep that in mind. Javascript might be a good sub
Im not on my pc rn so i cant open discord
Then ask again when you'll be on your PC
I have 15 minutes to fix this problem
11 rn
Can you open discord in a private tab ?
All I can say is, make sure the method that should run when you click the button is actually running
Place a Debug.Log() in it, write something meaningful and run the game, click the button, see if you get the message in the console
!code please post properly
๐ 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.
Why this happens
I POSTED NORMALY NOW
No you didn't. You posted a large amount of plain text that I deleted, and above is also a large codeblock not posted as a link
THIS SERVER SUCKS, BUT ITS MY LAST CHANCE TO GET HELP
Just read the post from the bot and follow the instructions without getting worked up about it
You arent even letting anyone help you because you havent posted it properly. I cannot even see your code on my phone, and not many people are gonna download files
It's really easy.
Click a link here
#archived-code-general message
Paste your code in.
Click save
Copy the url
Paste the url here
Then everyone can help
how do you blame the server for you not adhering to simple code sharing guidelines that make it easier for us to read the code to help ?
I DONT HAVE FREAKING TIME FOR THAT, AND THIS PROJECT IS THE MOST IMPORTANT IN KY LIFE, I DONT FREAKING KNOW WHY ITS STOPED WORKING, IT WORKED FINE BEFORE. AND NO ONE CAN HELP ME. IM DEAD
!mute 709639836402974732 30m take a break, go outside, and when you return please just post links to large codeblocks like our read-me and bot post states.
neilas_z was muted.
when i try to run BurstFov, the fov increase works seemingly fine, and then crashes upon running ResetFov. https://hastebin.com/share/ifafeleyol.csharp
your missing yield return null inside whileloop @hidden flicker
or yield for the coroutine if that's what you want to do instead
If you need to start the coroutine (line 27), and wait until it's finished to continue through the if statement (after line 27), then yield return StartCoroutine(...)
What does that mean? (Sorry, started actually learning coroutines literally yesterday)
SPR2 elaborated
So I put that line "yield return StartCoroutine(...)" where?
Kind of the opposite - I want to run ResetFov once the fov has been set to the desired value
Can you post the code again? Website says the contents was not found or deleted
Could be just on my end though
Yeah for sure, plus it'll be the current version after my modifications
Oh it's fixed wtf, I refreshed the page
Yeah so you can still yield return StartCoroutine() because what checks for the FOV reaching its target is the if statement on line 24 14
here's the current version so we're working with the same context https://hastebin.com/share/hihalogidu.csharp
Yielding the coroutine will just not allow the code to move past line 18, until the ResetFov() coroutine itself has completed. So when execution resumes say on line 19, the FOV will already be reset
That's true, but that sounds like the intended effect... ResetFov should run once fieldOfView.Equals(baseFov + changeBy)).
Yep that's what your code was doing even without the yield return on L18
Not sure why you added a "but" in the sentence there, the original condition is still in place, it's what happens after L18 that's delayed when you yield return it
Nothing should be happening after line 18, right?
It should just loop until the conditional of the while loop isn't met
It will loop again if the condition is met, correct
Without the yield return, it will loop immediately after line 18 was executed.
With the yield return, it will loop only after ResetFov() has finished running. If that takes 10 seconds to run, then the loop will start looping again after 10 seconds only
I understand it a little better now... but I'm still not sure how to make it run properly
What do you mean by "run properly" here?
- As long as the field of view is not equal to baseFov + changeBy:
- Move the field of view towards baseFov + changeBy
- If the field of view IS equal to baseFov + changeBy:
- Log that it ran ResetFov
- Run ResetFov
- Stop running BurstFov
i dont know which channel i would put this in but i cant move this or anything
i can only move terain
yield return null; to cover the case where the condition to run ResetFov() is not met (use else), and that's it. The code will do what you described here
To say it differently, the fact that you put yield return or not, acts on when step 6 will be "executed", right after the ResetFov() coroutine has started, or after it finished
This is the current version of the code. I think it's what you described (tried my best to follow it) but the FOV is now rapidly pulsing. https://hastebin.com/share/behequsaju.csharp
Aaaaand it apparently never runs ResetFov.
I'd say it's the way you compare the values in the while loop and if statement conditions. As these values are float it's very unlikely it will be exactly equal to what you're comparing it to
Instead of: if (a == b)
Prefer: if (Mathf.Abs(a - b) < some_small_value), or if (Mathf.Approximately(a, b))
The second one is an infinite loop, since you're not yielding when starting the inner coroutine
The crash indicates that the if statement passes
Got it. Why does the first one pulse though?
presumably the coroutine that is running is causing it, or some interaction where it's running quiclly and restarting, etc.. You need to debug further to find out exactly what's up
The loop never exits
check your logs, etc.
Ok. Iโll add some debugs and get back with the logs
using System.Collections;
using System.IO;
using UnityEngine;
public class RandomTextureLoader : MonoBehaviour
{
void Start()
{
LoadRandomTexture();
}
void LoadRandomTexture()
{
string texturesPath = "Assets/Textures/Walls"; // Change this if your folder is located elsewhere
string[] textureFiles = Directory.GetFiles(texturesPath, "*.png"); // Change the extension based on your texture types
if (textureFiles.Length > 0)
{
string randomTexturePath = textureFiles[Random.Range(0, textureFiles.Length)];
Texture2D texture = LoadTexture(randomTexturePath);
if (texture != null)
{
ApplyTextureToMesh(texture);
}
else
{
Debug.LogError("Failed to load texture: " + randomTexturePath);
}
}
else
{
Debug.LogError("No textures found in the specified folder: " + texturesPath);
}
}
void ApplyTextureToMesh(Texture2D texture)
{
MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null)
{
Material material = meshRenderer.material;
material.mainTexture = texture;
}
else
{
Debug.LogError("MeshRenderer component not found on the attached GameObject.");
}
}
Texture2D LoadTexture(string path)
{
byte[] fileData = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(fileData); // Auto-resize the texture based on the image file data
return texture;
}
}
Why isn't this loading the texture? I have the pngs in the Assets/Textures/Walls directory
Add more logs and/or show what logs are printing now.
anyone know how to get list of folders inside Resources folder?
Which resources folder? The project can have any number of such folders.
The code directly above us is an example of getting all files inside a folder, and can be modified slightly to get all folders inside a folder.
At runtime though, no such folders will actually exist
at runtime you can load resources from assets
https://docs.unity3d.com/ScriptReference/Resources.Load.html only works for things inside Resource folders
but also - the folder structure of your project will no longer exist in a build.
ohh
Only the paths for Resources assets will be saved in order to facilitate Resources.Load, but the folders themselves will not really exist
so there's no way to list the folders
No. Why are you trying to list the folders? What are you actually trying to accomplish?
Im trying to create a radio
and load at runtime the channels
every folder is a channel
Use ScriptableObjects imo. You can use https://docs.unity3d.com/ScriptReference/Resources.LoadAll.html and put them all in one folder
no I posted the right one for my suggestion.
public WeaponSO weapon_id
{
get
{
return weapon;
}
set
{
weapon = value;
UpdateWeaponType();
}
}```
any idea why that doesn't call the updateweapontype function?
Make public WeaponSO weapon;, private instead. You'll see the errors right away, I think you may be not using the property at all here
ok so, is there any way i can asign weapon_id in the editor or only by code?
Only by code. Unfortunately Unity cannot serialize properties in the Inspector
guess whos game still isnt working?
I believe you can, if your property is just a get; set;, you can use [field:SerializeField] on it
Ah
Is there a way to get "continuous collision detection"-like for triggers?
I have fast bullets (that should be trigger colliders) and sometimes they are moving to fast to detect trigger event.
Both object has dynamic body type with continuous collision detection.
You have to roll your own. A few lines of code that raycasts from the last bullet position (last frame) to the current bullet position can do. You won't even need the collider anymore, and you can extend it to a RaycastAll, if you need to compute penetration damage, what stops the bullet, etc.
I thought about it, but wanted to ask for the simpler built-in solution. But there is no such, right?
can someone please help me cause everytime i right click on my mouse the game keeps pausing?
Maybe there is a way to use usual colliders (without isTrigger) but without physics?
I need rigidbody to move them, but I don't want them to "push" object they are interacting with.
Oh, you can set their mass to a very small value
Input 0, and it'll set the value that's closest to zero that's not zero. A few micrograms or less
But if the projectile is big and small, and spawns inside of an enemy it still pushes them
Also I need actual mass because I'm using force movement for theme
I remember seeing some property on the Collision object passed in OnCollisionEnter that's the force that was applied to the receiving object. You can apply an equal and opposite force to cancel it out
Alright I got some debug stuff in.
I don't think OnControllerColliderHit detects trigger colliders
You might want to switch to the regular OnTriggerEnter for this
Maybe this is relevant
https://forum.unity.com/threads/character-controller-collides-a-trigger.172373/
I have a 3D game, objects in the form of a tilemap
the prefab of the road itself
Hi,
I have issues with order of executions between when I setup a singleton manager and when I subscribe to an event it exposes :
GameManager.cs
using System;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public event Action OnPlayerDeath;
private void Awake()
{
Debug.Log("Executed second");
Instance = this;
}
public void GameOver()
{
if (OnPlayerDeath != null) OnPlayerDeath();
}
}
ObstacleController.cs
using UnityEngine;
public class ObstacleController : MonoBehaviour
{
private void OnEnable()
{
Debug.Log("Executed first");
GameManager.Instance.OnPlayerDeath += GameManager_OnPlayerDeath;
}
private void OnDisable()
{
GameManager.Instance.OnPlayerDeath -= GameManager_OnPlayerDeath;
}
private void GameManager_OnPlayerDeath()
{
// do stuff
}
}
Here, ObstacleController.OnEnable() is executed before GameManager.Awake() therefore, I get a null ref when trying to access the GameManager instance.
I do not want to fix this by messing around with the scripts execution order as I feel this is not a robust solution and I might break it with future changes/refactors.
When would you setup the GameManager singleton in order to ensure its exposed event is available for other scripts to subscribe to ?
Or would you move the subscription code in ObstacleController to another spot in its lifecycle ?
Looking for best practices here please ๐
Thank you
Awake: initialize yourself
Start: get references from others
OnEnable runs directly after Awake, it's not like Start which runs when all other script's Awake have finished running
so I should subscribe to events in Start() method ?
Yes
Also, how to enable "Continuous Dynamic"? I don't have this option. Version 2021.3f
2D doesn't have that, only 3D rigidbodies do
alright, thank you.
most of examples i've seen about events always managed subscriptions in OnEnable/OnDisable
would you still unsubscribe in OnDisable() ?
Only if you need the event handlers to not run when the object is disabled. Else, you unsubscribe in OnDestroy() so everything is cleaned up when the object/script is destroyed
got it, ty
If these are to be pooled and reused at later times with subscription, you'll want to consider leaving the subscription service to the object pooler.
is there a list type like dictionaries but they can have repeating keys
Just store a list as the value
can you elaborate
What does repeating keys imply? Multiple keys to 1 value?