#💻┃code-beginner
1 messages · Page 337 of 1
var layerName = LayerMask.LayerToName(other.callbackLayers.value);
Why is this Layer index out of bounds
protected override void OnTriggerEnter2D(Collider2D other)
I want to get the layer of the colliding object
callbackLayers is a LayerMask, not a layer
Ahhh yes, its gameObject.layer
I try to launch a misle out of an rpg. I have a bad time understanding how coroutines work. Below a method that starts coroutine that lerps misle object and when its done play particle effect and call other method. But lerping works only if i put playing particles and explode method inside of the coroutine. Otherwise misle explodes instantly at the hit point. Shouldn't those two be called only after coroutine is done??
public void SetFlying(RPGEffectsManager effects, RaycastHit hit)
{
StartCoroutine(Fly(hit,effects));
effects.PlayExplosionEffect(hit.point, Quaternion.identity);// should be inside coroutine
Explode(transform.position);// thats too
}
private IEnumerator Fly(RaycastHit hit, RPGEffectsManager effects)
{
Vector3 startPos = transform.position;
float distance = Vector3.Distance(transform.position, hit.point);
float remainingDistance = distance;
while (remainingDistance > 0)
{
float distanceCovered = 1 - (remainingDistance / distance);
transform.position = Vector3.Lerp(startPos, hit.point,
distanceCovered);
remainingDistance -= Time.deltaTime * _speed;
yield return null;
}
transform.position = hit.point;
}
So, appareanly coroutines don't suspend the code that goes after them?
correct
you do misunderstand coroutines.
when you start a coroutine it will run until the first yield statement. Then the code after the start coroutine will execute
...hello?
Nobody gave you a solution, but you can fix this by making SetFlying a Coroutine itself. Then you yield the StartCoroutine inside and it will wait for it to finish.
yield return StartCoroutine(WaitAndPrint(2.0f));, like this for example
Thanks man😁 , but i found solution, I just put play effect statement and Explode method call inside the coroutine
Works too. Just keep it in mind because it might be better to separate the logic into its own chunks
i mentioned down bellow where i mentioned inthe comment there, below the video
like when i testes in the stage scene, and when i die and respawn, it actually works that i can move around and that i was respawned there, but however. when i was in a different scene, which is a level select scene and when i tested there. clicking on the first level to go over to that scene, and when i die and respawn. I am not respawning anymore
i did say that below the video
!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.
Alright. So, you can respawn endlessly on one scene, but just once on the other. Is it right?
If you're following a tutorial, and something works in the tutorial but not yours.. you did something wrong, go back over the tutorial
or the tutorial is bad/outdated lol
I even tried copying the same exact code
do the code link services add code highlighting or anything to the code?
then you still did it wrong
colours the code, yes
would be lot more readable than that txt I guess?
Yes
no i meant that when i playtested in that level scene it works, but when i playtested when i'm in a level select scene and select a level and went over to that scene, it no longer works anymore
And the txt has to be downloaded too
what?
Right, so what is wrong in my statement?
I wasn't referring to you
i can respawn so much and lose a life in the level scene, but when I'm in a level select scene and slelect a level and went over to that level scene, when i die, I doesn't respawn anymore
Is the respawn logic managed by some kind of static or DDOL script?
#💻┃code-beginner message there was a error when i die and doesn't respawn, and took me over to line 52
What error
I see in the video, its a null ref exception.
now add Debug.Logs() until you figure out where the problem is and then try to fix it yourself
if you can't fix it then come back here, don't just dump your entire class here and ask for someone else to do your work lol
yeah. i meant error as in the color red https://gdl.space/iwiqexopok.cs
You have a NullReferenceException. Is your Singleton null?
Yes, it's a NullReferenceException, which appears when trying to access something from null
then how do i fix it?
Read my previous message
i meant how can i acces something from null?
is using Debug.Log a good way to debug code (for beginners) or is there a better way I should be using?
You cannot. That's why it gives you an error.
much better way, the debugger in your IDE
It's generally a good way. You may want to use MonoBehavior.print, which just calls the Debug.Log.
You usually use your IDE's debugger when it's something you want to have a closer look at, but when having the values, which are constantly changed in Update, you won't be able to properly debug them without simply printing something.
It’s what I use but the vs debugger is better
is there a guide around here how to set it up?
in pinned messages
cool thx
Right, so what is it supposed to mean?
this is a null which is instance, and that line which i was sent to have
PlayerComponents go = PlayerManager.instance.SpawnPlayer(1, PlayerManager.instance.GetPlayer(1).player2D.lastCheckpoint.transform.position);
doe sit have something do do witht he instance null?
Well, yeah, it probably does
It's either your PlayerManager or the instance is null
Check it out
Do you know what null means?
not so much
i don't know which is null..
Then you can start at the start https://unity.huh.how/runtime-exceptions/nullreferenceexception
Imagine, you want to eat an apple, which is on your table. You try to bite it, but you cannot, because this apple doesn't exist on your table. This is what throws you an error.
Oh that’s why my teeth hurt when I bite the table
And so imagine spawning a player from the PlayerManager, which doesn't exist and thus doesn't even have its instance
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Your teeth cannot hurt when biting a table, as the process breaks after the error is thrown. You might have miscalculated something.
void Awake()
{
if (instance == null)
{
instance = new PlayerManager();
}
}
like this?
No
Ah…
You may want to use a complete Singleton pattern
like... private static Singleton singletonInstance = null;?
There is also a link on the link they sent
No, why would you make an instance not accessible?
no this is not the same one
void Awake()
{
instance = this;
}
?
THIS https://unity.huh.how/references/singletons ... was linked to from the link you've been given, it helps to read further
so I uh fixed it, but I can only jump in the air
its like very op
imma try another tutorial;
https://gdl.space/ibaxogokab.cs
this is from the PlayerManager script
the void awake
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
instance = PlayerManager.this;
}?
@hushed hinge You need to try it instead of sending everything here with a ?
If you insist on occupying this entire channel again, make a thread.
i am trying
singleton
there, a thread
singleton playermanager
made a new one instead
I just don't know if it's right
Others can see when a thread is created, there's no need to tell everyone
this is a code channel, delete and ask in #💻┃unity-talk
oof
it was like checkpoint.SpawnNewPlayer (system.boolean. player1) in checkpoint.cs:52
What line is 52?
Do you know what a null reference is?
I remember it has something to do with an apple and a table
i did read about it what the links they sent to me
PlayerComponents go = PlayerManager.instance.SpawnPlayer(2, PlayerManager.instance.GetPlayer(2).player2D.lastCheckpoint.transform.position);
it really sounds like you would be better of not using singletons for now and just practice coding more until you're ready for them
does somebody know why unity playes music so terrible and how to solve it
wdym by terrible? show the settings of the AudioSource also
it's like broken, the volume changes and it has that sound as if it would crash
are you trying to play it through code at all?
maybe its in Update or something and its being spammed play and creating that effect
i'm playing it through code yeah
show 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.
using System.Collections.Generic;
using UnityEngine;
public class MusicScript : MonoBehaviour
{
public AudioSource source;
public AudioClip clip;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
source.PlayOneShot(clip);
}
}```
yeah so you play it then it loops i guess
turn of looping on the audio source maybe
it's the same
take it out of Update
ok
it works ty
another question: I made Flappy Bird and i added pressure plates that should set a bool to true which is the condition to get the point when you fly through the pipes and this doesn't just increase the score it also sets the bool to false so you have to activate the next plate but the bool changes all the time
show the code
{
if (collision.gameObject.layer == 6)
{
plateActive = true;
Debug.Log("Treffer!");
this.gameObject.GetComponent<SpriteRenderer>().sprite = ActivePlate;
}
}
}```
this is the plate script
{
if (collision.gameObject.layer == 3 && active.plateActive && status.birdIsAlive)
{
logic.addScore(1);
active.plateActive = false;
Debug.Log("Punkt erzielt!");
}
}
}```
this it the pipemiddlescript
i've got 2 scripts cause the pipe has to collide with the bird and the plate with the arrow that is shot by the bird
i have already tried to change it to exit it doesn't change the problem
why does the pipe have to collide with the bird? it just needs to collide with the plate from what i understand
wait i'll send a recording
use a .mp4 or upload to streamable/youtube or something
looks like it works fine tbh? whats the problem?
flabby birb
the problem with the bool chaning is that sometimes i get a point without the plate beeing active and sometimes it's reversed
the strange thing is: with the first pipe there is no problem at the beginning of the game it's only false then it's only true when the plate is active
wait i'll show the log
how to show the log obs only records the gameview
and this is when the first plate gets activated
what should i do in useful positions?
the plateActive bool is displayed
and it's changing
the interesting thing is that the log shows always the same order of false and true only once a second one of the lines changes
and if the last one is true the score will be increased if not it won't
do you know why the bool is changing all the time
Would anyone know if for loops are more efficient than foreach loops? I was watching a video a couple of days ago and the guy mentioned that foreach add to the whole garbage collection thing, but I've never heard that before so was just curious.
for is slightly more efficient than foreach
Okay cool. Thanks 🙂
forloop is best loop
The compiler can be smart about this. When using arrays or Span, there's no difference in the compiled output between a standard for loop and a foreach. And whether there's any garbage allocated in a foreach depends on what you're enumerating. Most of the collection types in System.Collections.Generic implement a struct enumerator to avoid allocations.
Okay thanks fellas 🙂 Much appreciated. 🙂
i'm all for one, not all foreach . . .
List<T> has a struct-based enumerator that doesn't produce any garbage
I ran into an interesting issue once where a library that provided non-GC equivalents to LINQ methods was...producing garbage
its own struct enumerator type (or was it the enumerable type?) was getting boxed
...you know, if I had finished reading your message instead of hurrying to share a factoid, I'd have saved myself the typing 😛
I'm in this picture and I don't like it
I've run into the boxing issue with LINQ as well. It's an unfortunate limitation, but at least it's not any worse than if the enumerator was a class to begin with. I've implemented pooled class enumerators to try to get the best of both worlds. foreach will call Dispose on your enumerator so you can return it back to a pool.
I'm using https://github.com/asc-community/HonkPerf.NET in a lot of places
Instead of IEnumerable<T>, it builds up a terrifyingly complicated struct type
no garbage, no virtual method calls, no mercy

var res = acc;
while (prev.enumerator.MoveNext())
res = agg.Invoke(res, prev.enumerator.Current);
I replaced a foreach with this to get rid of that bit of garbage.
This looks evil because it's just kind of ... accessing an enumerator, but that's how the RefLinqEnumerable type works. GetEnumerator() just returns an enumerator field
hey, it hasn't failed yet 😁
i've been tilting-at-windmills to get my allocations as low as possible
so that I can crank up the complexity of my AI system and generate more garbage
amusingly, I learned about this on a SO question about...implementing a pool
to efficiently implement a pool, use a pool
For a platformer I want to add head collision evasion. How can I cast a raycast to check if there would be a collider that is not a trigger?
Ah I see cheers
I'd be curious how this performance in IL2CPP. I'm all for generics abuse to avoid allocations, but it can generate a lot of code. Before shared generics for value types was an option in IL2CPP, I was getting failed builds because all my generics abuse was generating 9+ **giga**bytes of generated .cpp files. Full Generic Sharing fixed that, but there's some reduced runtime performance that comes with that.
I'm not too well-versed on that!
I hadn't heard of full generic sharing; that's neat
I haven't done much with IL2CPP yet (partially beacuse it was blowing up on my macbook until recently...)
right now i'm more worried about creating 3 quadrillion shader variants
This does not seem to exist for 2D
Raycast2D uses a more complex ContactFilter2D struct
You can create an instance that does nothing with ContactFilter2D.NoFilter()
Then you can set properties on it to add some rules
note that the default ContactFilter2D doesn't mean "no filtering"
notably, its layer mask is empty
i made a public static class with specific public static readonly ContactFilter2D, so I could use throughought project, and update as new layers/etc are added. It has been very convenient.
(And i recommend this strat)
it might actually be public static readonly LayerMask, and public static ContactFilter2D with private setter public getter
Think I got it!
Just wondering why the array is not out, wouldn't that make more sense?
Physics2D.Raycast(transform.position, Vector2.up, _headEvasionFilter, out RaycastHit2D[] hits, _headEvasionRange);
it doesn't assign a new array into your variable
it modifies the contents of your array
assigning a new array would defeat the purpose, since it would have to allocate a new array and generate garbage
Huh? I thought it gives me an array of all hits it finds
It fills your array.
It would give you an array if it had the out parameter, yes
but it doesn't!
so i guess i won't find a solution for my plateActive problem. but when i put the music in the start function how to make it loop
So RaycastHit2D[] hits = { }; would be fine?
no, because that'd be an empty array
arrays can't change size
it would write zero hits into your array
But how would I know the size in a dynamic game
There's another variant of the method that takes a List<RaycastHit2D>. I find that more convenient.
If you used an array, you would guess a reasonable size based on how many hits you expect to have
maybe 8 or something
You don't know. You assume how much there might be.
I'd suggest having a single static list, so that you aren't creating and throwing out the list every time
So for my case where I just want to detect if the player would hit his head, a size of one would suffice
I'm not sure if it guarantees that it fills the array in order
I know that some methods make no guarantees about that
Although, it would be kind of hard to use Raycast if it gave results in random order
Arrays are cheap memory wise make it 100 or even more
And how do I check if it worked?
if (hits[0].)
look at the return type of the method.
If you only need to know the first thing the raycast hits, then you don't need to give it an array. You can use the overload that returns RaycastHit2D.
the problem is that this doesn't let you tell it to use triggers
it doesn't take a ContactFilter2D
(and then change it back afterwards!)
alternatively, just use an array of one element and don't worry about it
(or to not use triggers :p )
So I did it right?
I don't know what you wrote
private ContactFilter2D _headEvasionFilter = new ContactFilter2D().NoFilter();
// AWAKE
_headEvasionFilter.useTriggers = false;
// JUMP METHOD
if (_enableHeadEvasion)
{
var hits = new RaycastHit2D[1];
var amountOfWrittenHits = Physics2D.Raycast(transform.position, Vector2.up, _headEvasionFilter, hits,
_headEvasionRange);
if (amountOfWrittenHits > 0)
{
// The player WOULD hit his head, so perform evasion to guide them
}
}
when i put my music in update it sounds terrible but when i put it in start it doesn't loop
{
public AudioSource source;
public AudioClip clip;
// Start is called before the first frame update
void Start()
{
source.PlayOneShot(clip);
}
// Update is called once per frame
void Update()
{
}
}```
When it's in update, what are you doing to prevent it from starting over every frame?
Also, you're asking why playing a one-shot doesn't loop?
i don't know it worked
Do you know what one-shot means
This isn't a unity thing, this is an English thing
One Shot means exactly that. It plays once
Regardless of loop settings
@dreamy junco you know that Update runs every frame right?
would be wild not knowing considering the comment above it lol
what? You expect people to READ, silly you
yeah but it ruins the music
Right because it's starting every frame
it then sounds terrible
that's probably not what you want
yeah
yes, because you are telling it to start the music EVERY FRAME
So, start it once, and don't use the method that specifically ignores looping settings
Hey guys, is it necessary for a game object to have collider to be hit by raycast ?
yes
Hi, I ran into a similar issue before and couldn't figure it out.
I am rotating an object and the script I have works fine for the most part.
Issue is when I go < -90 or > 90 degrees on X axis.
It inverts the rotation applied to the object.
This causes fast switching as it's constantly going below and above the said number or just inverted rotation till you get out of that range(depending on the implementation).
I am really bad at math and this seems to be related to how quaternions work(I could be wrong) so I'd really appreciate somebody helping me figure this out.
I'd be glad to provide a short video showcase if the issue is unclear.
Here's the script and thanks in advance!
Conquer The Astrid. Contribute to nnra6864/ConquerTheAstrid development by creating an account on GitHub.
Considering it’s part of physics yes lol
Track the X value internally and then set the x rotation to match the internal value
I see, I did come up with the solution of tracking the rotation as a euler and then assign that euler back to the rotation.
I was hoping somebody had an explanation as to why this is happening or how to solve it without an additional variable(no particular reason for this).
Just tracking a possibly huge number feels odd and not like the right way to go if that makes sense.
Well you can internally clamp it to loop from 360 to 0 or whatever is needed but it’s because 270 is also -90, and the quaternion system is just the “shortest” rotation which sometimes translates weirdly to eular
But the variable is the best way I’m aware of and isn’t going to impact anything realistically
I see, so understanding why exactly it's happening would require additional math knowledge(specifically quaternions and to euler conversion), thanks anyways, imma just go the easy route ig
Specifically into quaternions and quaternion-eular math yes
Something I have little personal knowledge in yet lol
Hey! Beginner here
I'm making a marble game where I want to make the camera follow the marble from behind always, no matter where it goes or how it rotates. I suppose the best way to achieve this is to take where the rigidbody is moving (so velocity?), flip that and add it to the marbles position, with a bit of distance and height added we have the cameras position? Or am I overcomplicating things and there is a way simpler way to do this
Hey guys, do anyone have extensive documentation on the unity tilemap components ans related? All I found was a single page on it...
Just use Cinemachine
Either you can make your own camera system or you could use Cinemachine’s camera system, for freelook. (Cinemachine is an package unity provides)
True
I did give Cinemachine a shot but got completely lost on what things to set and use, but I will give it another shot, thanks!
The setup you described would take about 10 seconds to set up in Cinemachine
Ohh, I guess I will look at a few tutorials to see how it works, thank you
keeps giving me this error, i've been trying to fix it for wayy to long https://pastebin.com/7pSPHkWJ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the script you shared is not related to the errors
it's the exact same script?
PlayerMovement and PlayerMovementAdvanced?
oh wait mb
wrong one
sorry
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
looks pretty clear you're putting a bool somewhere that a float is expected and vice versa though
Is this up to date? Line 94 is empty
yeah
Make sure your script files are saved and then shjow the full error message
I even tried copying the exact same script
Show the full error in the unity console
What Body mode would you recommend for this btw?
what the hell
Transposer would be the most basic
like 300 errors just spawned outta no where
goddam
guess I have to rewrite the entire thing
you probably duplicated your script or something
hmm im currently trying transposer with world space as binding mode
Or just start at the top and the issues will probably fix themselves as you go
Syntax errors beget syntax errors
Sounds good
it will follow with whatever offset you set
what is it doing? Maybe share your setup in #🎥┃cinemachine
Looks like you defined readyToJump as a float
I tried ||
ohhhh
right click on readyToJump and click "Go To Declaration" or whatever it's called
looks like your MyInput function is expecting a bool parameter
but your GetReadyToJump function returns a float
you're again trying to shove a square peg in a round hole
What type is GetReadyToJump() and what type does MyInput expect
input expects a bool but get ready to jump is a float
https://poki.com/en/g/longcat
Hey guys, I was told to remake this game, but not using collider, and in 2D
I used to make a game like this.
But that game required collider
exactly
So those would need to match. You're going to have to decide which one needs to change
Looks like it's just grid based, no need for colliders
you can implement your own collision by just looking up if the grid space is occupied.
Should MyInput expect a float, or should GetReadyToJump return a bool? Only you can decide
I moved it there
So the game I made in the past was a 3D game, the player shoots raycasts around him so he can identify the final destination he can reach once moved, so the movement would be precise.
Can you tell me more about your idea ?
Implementing my own collision ??
Wow that sounds really complicated
I mean I just explained it. You basically have a 2D grid. to do a "raycast" you just do a for loop over all the squares in a line from a starting point in the desired direction until you see an obstacle
it's extremely simple
you just have a 2d grid
and you check if the space is occupied or not
If a grid cell is an object that knows what's in it, you can just check if that cell has something in it
If a cell has something in it, then that'd be a collision
What ?
I have never heard of this grid before
you're overthinking it
imagine:
bool[,] grid = new bool[10,10];
// Is space 4, 5 occupied?
bool isOccupied = grid[4, 5];
// mark position 1, 3 as occupied:
grid[1, 3] = true;
// mark position 6, 3 as NOT occupied:
grid[6, 3] = false;
in reality you'd probably use something a little fancier than bool but this is the simple base case.
Is this 2D grid something I can learn about on Youtube ?
It's just a basic concept
it's not really... a special thing you'd learn about on Youtube
Okay so ...
I have a 2D array, I each element is a block
I spawn the blocks based on the array ?
i didn't know it's possible to check if an array index is occupied this way, i thought it's done by checking if it's null or not
in my example it's an array of bool
so i'm just checking if it's true/false
bool cannot be null
ah, right, i didn't notice that
if it was an array of a class you could certianly use null to represent unoccupied
in general you're right, you can only check the value at a particular index in the array. The semantics of that depend on what kind of thing is stored in the array.
Am I right ?
yes something like this.
Is the [Min] attribute actually enforced?
Cause I can set values less than that in the inspector fields
you could use bool? then it can be null, true or false
Trinary! 0, 1, and "Eh, kinda?"
Unity doesn't have a [Min] attribute for the inspector
only a [Range]
Not there yet ?
Not exactly what you meant ?
Well I mean you'd have to actually go and define what a "block" is
Unused, Unoccupied, Occupied
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
"On", "Off", and "What the hell is a switch"
I see. Yes it should be enforced, but only in the inspector
if it's not you could report a bug
Don't mock, it's useful for representing non rectangular grid structures in a grid rather than using a jagged array
Mm yes it seems bugged then
how can i access workloads tab on vistual studio code if already have it installed?
So imagine this is a 6x6 grid, starts from the top left corner and move toward the right.
The first element of the 2D array's gonna be a blank block, the next one is also gonna be a blank block, but the next 2 elements are going to be a wall block which player cannot move on
yes
So my idea is valid ?
yes
Thank you
i've made a sound that plays when you press a button but the quit game button and the play button don't make a sound cause the game is quit or restarted
is there an easy solution
You would need the thing that plays sounds (and the audio source) to survive the scene reload
this means either additive scene loading/unloading, or the use of DDOL objects
wait for the sound to finish playing before taking action
i'll make a delay so it doesn't quit instantly
plz
Huh ?
the tab where i can install the unity things for visual studio i forgot to check them when i installed it
Open the Visual Studio Installer via Search bar and modify them
my invoke doesn't work it doesn't delay my function
you'd have to show your code
Well, share the code then
and explain what it's doing instead
{
Invoke("invoke", 1000);
}
void invoke()
{
source.Play();
}```
You.. delay the sound.
Not the quit/play functionality
And Invoke takes time in seconds
oh i'm such an idiot sry
Maybe someone have suggestion. I'm working on my thesis that is 3D game. I added lockers system where player can hide inside it, basically just pressing E for interaction and then player camera turns off and camera inside locker turns on, very basic. But I duplicated few more lockers and on first enter to locker it does not turn the right camera on and only if you exit and re enter locker you get right lockers view.
Hello I am trying to write my first 3d player movement script but I got my movent almost done but just added my jump function but now I can move whilst in air but not when on the ground whilst in air
I am not getting any errors (and yes I debuged Grounded grounded = true when on the ground)
code: https://paste.ofcode.org/B8CvgS2xizvmPME5jKrTZ8
i just wanna trigger an audio source with an auido clip inside cant i just play instead of playclipatpoint?
Yes you can just call Play to play the clip assigned to the source
now I can move whilst in air but not when on the ground whilst in air
What?
My moventscript includes aircontrol so when I am in the air the player can move but when on the ground I cant move
ps:
GroundCheckTransform = GroundCheck.GetComponent<Transform>();
can just be
GroundCheckTransform = GroundCheck.transform;
Or better yet - just assign the Transform directly in the inspector.
maybe you're just not applying enough force to overcome friction with the ground
Wow lmao XD that was legit it well ty
So you have a few lockers and cameras?
I would suggest serializing a List of the lockers and their cameras.
You cannot serialize a tuple in the Inspector, so you should create a struct.
[SerializeField] private List<Locker> lockers = new();
Where Locker.locker & Locker.camera. And think of a better name.
Invoke(nameof(invoke), 1000);
but you should learn how to use Coroutines anyway
Heyy quick question - does anyone know a good Unity tutorial for kind of beginners??
how do i make it so i cna crouch
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
code
Thanks! Ive tried some before ill try out more tho
fr?
yeah 100%
You may try finding a built-in Unity script tho. Like CrouchController or so
didyou start with the pathways ? those are the good ones to start
Imo one of the best ones
https://www.youtube.com/watch?v=-XNm7dPVVOQ
Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
Join me and learn your way through the Unity Game Engin...
they even do the Lerp correctly
I think it was just one tut from Unity sites but I will try some of these, thanks so much!!
check the ones pinned on this channel, they are pretty good
I will thanks!
why my funciton dont show here?
because you dragged script from Project view
not the object that has the script
Drag in an instance of the script not the text document the code is written in
Drag in an object with the script on it
ah i hjave to drag the game object
thanks yall
how do i send the value of the slider here tho?
You need dynamic parameter (should be the top ones)
if it doesn't show then i dont think you can do that via that component
Use the version of the function from the dynamic section, not the static one
It will be the top section in the menu
i think this not the way
I am so stuck...
sprays WD-40
can you show what list it shows you in the dropdown
there should be one next to the Volume that says Dynamic
...uhh..what?
ah not it worked it was the top one, thanks!
oh, because I don't know what WD-40 was. I was just ot feeling so good, because I am so stuck on something...
lol yeah probably bcuz a US product.
Anyway...whats the problem because you haven't explained anyway
well... iit's something in a thread. I know they explained a lot. but I still don't know how I can assign the variables becaus ein level select scene. I can't assign anything
why can't you assign anything
(UK too)
Ahh ok good to know lol
I don't know, I know I have the data, but I can't assign it in the level select scene (it is that the players in the gameplay scene are assigned, but not in the level select*
yes you cannot assign objects from one scene with objects in another
does that work across scenes?
yea
huh... good to know
I am still stuck on what I'm doing...
I'm kinda jumping in here so I'm not sure what You did and didn't do. I have to be at work in 20 mins so can't fully commit to a thread, but I'd start by learning first how to work with a singleton
use a separate project if you must practice
keep practicing how Singleton will work
so just to double check, if I declare a singleton in scene A and do stuff with it, I can reference it in scene B and the data will only stop persisting after a restart?
the data would only persists if singleton is in DDOl
well a singleton gets transfered over to the new scene with a DontDestroyOnLoad
otherwise unity likes to destroy objects on scene changes
public PlayerComponents GetPlayer(int playerNum)
{
if (playerNum == 1) return playerOne;
else return playerTwo;
}
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// Call your function here
YourFunction();
}
private void YourFunction()
{
GameObject.FindGameObjectWithTag("Player");
GameObject.FindGameObjectWithTag("Player 2");
}
still handy but closer to the behaviour I expected
singleton just makes it possible to be easy to access because instance is Static
which is through the whole Program
yeah
for my enemy AI how often should my enemy check for actions and chose an action, should i have it check every 3 seconds or is there other ways to do this better?
it is singleton
public class OSSManager : MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(this);
}
}```
I was on my verge of breaking down...
should probably DDOL some of the scripts I have now I think about it...
this is not a singleton
singleton is a pattern
i like to use a simple DDOL on awake and put it on a gameobject.. and then just nest all my managers under that gameobject
I have some hacky stuff to make a singleton superclass (yeye I know technically not a singleton or smart, but it saves my sanity) so it would be really easy to just add a DDOL to it
ok so if you have a singleton , you just use instance any time to access this object
They already have a function that runs when the scene loads. They also have a working find inside of it. They just don't know how to assign a variable.
i also have one of those
Ohhh right,yeah i figured they were missing something... there it is.. lol
using UnityEngine;
public class TestScript : Singleton<TestScript>
``` simple as this
so back at square one
And after 11 hours I refuse to tell them how to assign it
Smoothdamp Calls interfere with eachother.
Because it should not have come to this
I'm glad to know I'm both not the only one who's done this, and also that we have very similar methods
can we move to #archived-code-general and discuss it?
yeah after so much hand holding , they manage to retain 0 of that info lol
it's just not that I don't know how to assign it in the level select scene, it just that I can't assign anything there
i use singletons so often its just smart to have a generic singleton class
I am using the instance. and that when i was playing in the gameplay scene, when I die and respawn it works. but when I'm in level select scene and goes over to the gameplay scene and when I die, I can no longer respawn
You need to assign the player variables when the scene changes
Instead of trying to start the whole debugging process over again with new people you could just actually do what you were told to do
You're going to have to do that either way
they are assigned in the gameplay scene. yet I can't assign them in the level select scene, nothing in the scene, nothing in the assets, nothing else
You have a function that runs when a scene is loaded
yes
There's no need for any thread or any more posts on it. You literally have the answer
you just have to assign the variables to the data you've gotten
No more questions on this. Don't rope random people into starting the entire goddamn process over because you don't know how to assign a variable. You aren't gonna know how to do it in six hours of spawn or nav debugging the same goddamn steps either
when you said assign them, i was confused if you meant in untiy or in the code
I literally gave you a step by step process of creating a function in a script and how to use code to get the data
how could that mean anything else
Now, back into the thread and woe betide anyone who follows you into it
been helping them a lil in the thread just now and we're almost there
darn (no gif)
don't crosspost
Whenevr I try install xr plug-in management it always has an error
I need help with that
also don't tag someone not in active convo with you
Sorry.
also "an error" is very very vague
especially in the field of dev
the error 
Sorry ill let you know what the error is lol.
Basically saying ‘buildtargetgroup’ does not contain a definition for ‘VisionOS’
hard to say without knowing what exactly you've done, what you're trying to do etc.
read the #854851968446365696 on the DOs
What I’m trying to do is install the XR plug-in management
thank you
I think the others did most of the work tbh so if you didn't thank them already I would
Read that^
I'm fairly new to the Input System. I followed a tutorial and they gave me this code: ```cs
InputAction jumpAction;
void JumpTriggered(){get; set;}
void Awake(){
jumpAction.performed += context => JumpTriggered = true;
jumpAction.canceled += context => JumpTriggered = false;
}```
It works and is really good if I wanted to hold a button down. But I don't want that. How can I make it just perform once (Like I need to tap it instead)?
huh which version of unity is this ?
It’s 2023.2.20f1
thank everyone.
why are you using that instead of LTS
just do something immediately instead of setting JumpTriggered to true
Ideally yes
note that the performed event will only fire once until you've released the button and pressed it again
2023 isnt a thing anymore anyway, Unity is now either LTS 2022 or 6 preview
Ok which one is lts?
Ok so that or the 60000
The 6 with loads of 0s lol
6 is preview not lts
I know that VisionOS was present as some weird codename for a while (i do not remember what it is)
Ok
i'm guessing your project contains code that is still using the old name
Ok lol
Yep
So I’ll get lts 2022
Hi everyone, just wanna ask how do I put some kind of force to this instantiated object(static speed<not slowing down>)? https://hatebin.com/elilkacipu
you need a Rigidbody and to set the velocity
Instantiate returns you the Object created
access the Rigidbody or whatever from there
cannot press ui buttons and idk what i m doing wrong?
debug it with Event System in playmode
inspecting the Event System object (which should have an Event System component on it) will let you see what you're hovering over, yes
assuming you are not using the new input system, which doesn't tell you that, for some reason
you probably have a large UI element that's blocking the other buttons
So... by setting its velocity to for example 5 will make it travel by the same speed until idk maybe a collision
(even though it may not visibly cover the buttons)
i have big black square
yep
oh, cool THX 👍
that is what setting a velocity does, like cruise control on a car
so ?
select the "Event System" object in your hierarchy and look in the inspector as you try to click on things
you should see some information about the currently selected game object, as well as what you are hovering over
Which 2022 should I do.
sorry, for bothering again but how do I reference my rigidbody of my bulletPrefab so I can set its velocity? https://hatebin.com/aspzklumld
Instead of referencing it as a GameObject, reference it as a Rigidbody
This will work as long as there is a Rigidbody on the root object of your prefab.
Now you'll get a Rigidbody back from Instantiate.
I don't know how to do that. jumpAction.performed isn't a bool. Is there a way to just have it work with the current system?
oh that is a possibility? 😄
do you not know what this syntax means?
context => JumpTriggered = true;
I do not
A common pattern is to create a component that holds all of the things you need
call it Bullet
This is creating an anonymous function -- it's a function that has no name.
compare this to a method, which has a name
It's equivalent to writing this method out
oooh, thanks I appreciate it
void SomeMethod(InputAction.CallbackContext context)
{
JumpTriggered = true;
}
Yeah
jumpAction.performed += SomeMethod;
Same idea.
So, instead of just setting a field to true, you can do whatever you want in there
One thing to note: subscribing with an anonymous function means you can't unsubscribe later
This is getting called on Awake
foo.performed += what => how;
foo.performed -= what => how;
This doesn't work. The two anonymous functions are different objects.
It's only an issue if you actually need to be able to unsubscribe
(notably, if you have Domain Reload disabled, you have to clean up after yourself between play sessions)
you also might want to unsubscribe when the behaviour is disabled
void OnEnable()
{
action.performed += HandleAction;
}
void OnDisable()
{
action.performed -= HandleAction;
}
void HandleAction(InputAction.CallbackContext ctx)
{
// whatever
}
like so
OnEnable runs immediately after Awake, so this has roughly the same timing as doing it in Awake
(unlike Start, which runs a frame later)
I do already
oh wait, I just realized something
If I want to just have it happen at a tap, what should go here then? ```cs
jumpAction.performed += here?
...this is inside of Update
you're subscribing every single frame
No
Oh yes you are. See the little + = in there?
performed isn't a boolean, as you observed
and += would be the wrong syntax for doing something conditionally anyway
It is in Awake()
the code you sent does not indicate this
if that code is inaccurate, then please show us your current code
?
void Update(){
jumpAction.performed += context => JumpTriggered = true;
jumpAction.canceled += context => JumpTriggered = false;
}
private void Awake() {
RegisterInputActions();
}void RegisterInputActions() {
moveAction.performed += context => MoveInput = context.ReadValue<Vector2>();
moveAction.canceled += context => MoveInput = Vector2.zero;
jumpAction.performed += context => JumpTriggered = true;
jumpAction.canceled += context => JumpTriggered = false;
}
This is the code 
OH, I messed up there
don't try to be clever when sharing code. copy-paste it directly.
you are just wasting our time
share the entire script so i can see what you're doing !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.
Which do I use? 
any link works
i use https://gdl.space
it has a pleasant background color
the bot message has several choices because sometimes the sites break
okay, so you're enabling the actions in OnEnable and disabling the actions in OnDisable
reasonable enough
note that this is separate from subscribing to performed (and maybe unsubscribing from it later)
Disabling the action means the input system completely stops thinking about it
nothing happens
I did that so when I change Scenes it doesn't have input
This code does not disable the action. It just says "hey, tell me when the action is performed" in OnEnable
and "stops telling me about that" in OnDisable
Are you saying that the issue is within OnEnable and OnDisable?
I see a problem with your code, although I thought you were just unsure about how to run some code in response to the performed event
the problem is that you never unsubsribe from those actions
suppose PlayerInputHandler turns on in scene A and subscribes to the events
then you switch to scene B
the old PlayerInputHandler is still subscribed to those events
In this case, I don't think it's going to cause any errors (all you do is store things in fields when the events are raised)
it is a "leak", though
O_O
the old PlayerInputHandler object will stick around forever
again, not exactly life-threatening
(from Unity's point of view, it's been destroyed -- but the C# object is still there!)
It shouldn't I am using a singleton?
Ah, if it's a singleton in DontDestroyOnLoad, then this is fine
which I just noticed 😛
So what can I do to make it tap only?
so you want nothing to happen at all if you press and hold?
or do you just want one thing to happen?
I just want the code to check if I pressed the "jumpAction". I don't want the Player to hold the "jumpAction" and keep jumping while holding.
I see.
So there are a few options here
One would be to have the player controller code set JumpTriggered back to false after using it
is there a funciton to completely restart the level, like reload it?
Another would be to have an "On Jump" event on the player input handler. You would invoke it when the action is performed
The player code could then subscribe to the event.
I'll try this
How can I check if I performed jumpAction?
well, presumably, your player controller has something like
if (input.JumpTriggered) {
// do a jump
}
you can just set JumpTriggered back to false here
loading a scene will destroy everything in the old scene
``` I usually use this
I'll check
ah, yeah, this lets you load whatever scene is currently active
which is exactly what you're looking for
note that SceneManager is in UnityEngine.SceneManagement, so you will need to add
using UnityEngine.SceneManagement;
Your IDE should suggest this.
I do this when I access the input from other scripts: cs inputHandler.JumpTriggered Is this the issue?
Well, this isn't the inputAction. This is the bool that changed when holding and letting go the InputAction
Yes. I am talking about that boolean field.
The input action isn't involved here at all
The InputAction is only effected here in the PlayerInputHandlerScriptcs jumpAction.performed += context => JumpTriggered = true; jumpAction.canceled += context => JumpTriggered = false; No where else
use Update
Yes, and again, the input action does not matter at all
or just do the thing in the performed callback
I will try
I'm not talking about jumpAction at all. I'm talking about JumpTriggered.
jumpAction.performed += context => // Actually do the jump here;```
and yes, I think it'd make more sense for the PlayerInputHandler to just do something directly in response to the jump action being performed
I need some variable to store that I did this. What can I use?
(it can raise its own event that other things subscribe to)
why do you need a variable?
I am accessing this code from another script
To do what?
To check if I pressed "jump" key
to do what? To do the jump?
Just have the other script listen to the event
or make your own event here
OnJump
Invoke it here and have the other script listen to that
A bool variable doesn't make sense unless it's like a continuous thing
or if it's something you might want to wait for a bit before consuming
It would be nice if you could press jump a few frames before hitting the ground.
or if you make a method like this to consume it:
public bool TryConsumeJump() {
bool toReturn = _isJumping;
_isJumping = false;
return toReturn;
}```
I am accessing it here in Update in JumpingScriptcs if (groundRememberTime < rememberTimeStop && inputHandler.JumpTriggered) { Jump(); }
You can do something like this:
#💻┃code-beginner message
okay, so just do inputHandler.JumpTriggered = false; and you're done
that's what I was suggesting earlier
And do:
if (groundRememberTime < rememberTimeStop && inputHandler.TryConsumeJump()) {
Fen's idea works too
How would I do that? I tried checking if jumpAction.performed then do that. But it isn't a bool.
by literally writing that exact line of code
jumpAction and JumpTriggered are two different variables
This? cs if (inputHandler.jumpAction.performed) { Jump(); }
is that the code I told you to write?
it doesn't look like it to me.
What solution did you send?
this line of code.
that would go into my JumpScript?
I don't understand on where you are saying to put that code
Correct. It would reset inputHandler.JumpTriggered back to false after performing a jump.
when you jump of course
I understand now! Thanks for the help both of you. 
!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.
this is my enemy AI script, on line 73 the 2nd time the enemy attempts to make an action i get a null reference
but it should already be set from the functions that run prior in the battle runtime -
void enemyRun()
{
enemyai.fillActions();
Action action = enemyai.ChooseAction();
//if (action != null) { Debug.Log(action); }
enemyai.PerformAction(action);
}
you probably have null entries in your actions list
it checks the action before adding it if their null
remember, calling Add on a list does not replace any of the already null elements in it, it adds new elements to the list
that does not prevent the list from already having null elements
if i set something on a list null it still exists
so i need to do some kind of Remove
list.Remove?
yes
ill try it out
also that loop in your Reset method is pointless, just clear the list
List.Clear
whats the difference
did you bother looking at what RemoveAll does?
it accepts a predicate not a type
oh something new to learn
- get your !IDE configured
- that is not the correct way to share !code
- rotate the bullet to face the gun's direction when you spawn it
📃 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.
damn, dyno doesn't like two commands in one message. !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Why is this always false?
if _isGrounded is true it won't evaluate that. so the only time that can be evaluated is when _isGrounded is false
did you bother reading point 3 in my original message? and did you configure your IDE yet?
Oh because || immediately exits the call
it worked, but if an invokerepeating starts after something is == true while in Update, will it keep running even if that is set to false?
cause thats whats happening to me
Hello is there an other way than transform.forward to get the orientation of a gameObject? because the forward is a vector and for example I don't know if it's facing me or not
InvokeRepeating has nothing to do with conditional statements. once you start it it does not stop until you tell it to (or the object is destroyed/disabled)
Why does transform.forward not work?
alright thanks
compare transform.forward with the vector facing you. Use Vector3.Angle. see if the angle is small enough
You would absolutely use transform.forward
A vector is exactly what you need
because the transform.forward returns the normal so not the direction
It returns the direction the object is facing
It absolutely returns the direction. What do you mean by "the normal"?
transform.forward is the direction that the object is facing along the Z axis (its forward axis)
the only time you wouldn't use transform.forward to get the direction an object is facing is when that object does not point along the Z axis (such as in 2d where objects typically point along the Y or X axes)
it returns this vector no ?
Yes, it returns the blue arrow on an object's transform gizmo
but even if it is oriented down it will return the same vector
no it won't
It will return the object's forward direction
set your tool handle to Local instead of Global and you'll see the object's actual forward direction
because it seems that the tool handle's orientation is confusing you when it comes to the actual orientation of the object
Is this 2D?
thanks
If it's a 2D game you might want the red arrow which is transform.right
no 3D
Ok then yes use forward
Hi I'm making a 2d game rn and I'm having trouble with a slider. I've made those before but for some reason it's not working. Ik its not the int because i see the health going down but the slider isnt moving
Show !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.
if the slider is for a health bar, i'd recommend using a filled image instead. but yeah, gotta show relevant code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //for text
public class Bosscontroller : MonoBehaviour {
public int health;
public int dropdmg;
public float velocity;
public Slider healthBar;
public bool candrop;
public bool restart = true;
Animator anim;
Rigidbody2D rb2d;
AudioSource aud;
// Use this for initialization
void Start () {
//componants
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
aud = GetComponent<AudioSource>();
//health bar stuff
healthBar = Instantiate(healthBar);
healthBar.maxValue = health;
healthBar.value = health;
//put in an for loop in an if
if (GameObject.Find("Player").GetComponent<Bossplayer>().hp >= 0)
{
//pause
Hover();
}
}
// Update is called once per frame
void Update () {
healthBar.value = health;
//keep from falling off
//check for edge platform
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Projectile")
{
Destroy(other.gameObject);//destroy bullet
health--;
if (health <= 0)
{
Destroy(healthBar.gameObject);
Destroy(gameObject);
}
}
}
Specifically, the first section Large Code Blocks
!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.
There should be a save button on the site.
well we need the link it generates after u press the save button
Then copy the url here <link>
We get line numbers, some kind of syntax highlighting and whatnot. Much more legible.
one thing to note is that you are instantiating a new Slider in Start but also not putting it on a canvas
i'd bet you are actually trying to use the existing slider rather than a clone of it
yes i dragged that into the scene so it is a child of the canvas
theres no clone of it
but you Instantiate a new one and use that new one. so there is a clone of it
remove line 28
How are you dragging in the clone your code makes in Start?
The game's already running by then
@slender nymph that fixed it thank u
can you also have a look at my method hover real quick? i think the issue is the x value isnt changing even though ik it is because it's coming from another script
Currently trying to create a system similar to black ops zombies where you have to collects different parts from places around the map and once you have collected all of them can build an item with. im trying to find a guide or any of sort of tutorial on how i would go about this but cant really find anything. if anyone has any knowladge and could point me in the right direction that would be much appricated. thanks.
how can i check in code if a particle system is emitting but its paused?
nvm found it
isPaused
what is it supposed to do. and how have you confirmed that the x variable isn't being changed
this is just your run of the mill crafting mechanic. i'm sure there are dozens of tutorials for that
the x value is taking the transform position of the player(which is tracked in update in another script) and teleporting above the postion of the player and then it drops
@slender nymph
that doesn't really answer any of what i asked
yea im trying to kind of change one to fit what im doing but they arent exact so was just wondering if anyone knew anything closer to what i needed
no tutorial is ever going to be exactly what you want. you need to watch the tutorial and understand what it does and why then adapt that knowledge to make what you want
ok the method is supposed to bring the enemy over the player but after the first time he just teleports to the same spot. It's supoosed to move where the player is moving
but you set the x value to 0 then immediately use that value as the global position instead of getting the player's actual position
trying to import a map/level/scene from one project to another. it has a lot of differenet prefabs and stuff and materials. i tried importing the entire scene but everything goes pink and materials arent showing up and it just keeps breaking every time i try and import it. not quite sure if theres a better way to do it but most places ive looked say to just drag and drop from one project to another but isnt working
is there an unscaled update i can use?
wdym by that
what are you trying to do, don't think update is scaled with anything
i want something to move around when timescale is 0
just wondering if that was possible
oh okay
thats fine then
thanks
i thought default update was also scaled with timesacle
You could use Time.unscaledDeltaTime for anything else
am i able to use waituntil bool == true without using a coroutine
why dont you want to use coroutine ?
i wanted to invoke repeat it, but that causes some issues by itself
invoke repeat kinda bad for this
i'm new to coroutine and asynchronous
sort of new
invoke and invokerepeat are mostly bad in general. you can explain the logic you're trying to do, and itll be way easier to help set it up with a coroutine
I still dont understand what issue you had with coroutine
just a note, coroutine and async are completely different
time to start learning
alright i'm currently afk in heading back to pc now, i'll show the functions that need to be run for the enemy AI
i'm inclined to agree
the script the repeat is in is large i'll cut off the unimportant bits real quick
'https://paste.ee/p/fR265' - the invoke repeating is on line 268, the function it runs is on 418
'https://paste.ee/p/3p50a' - this is the actual enemy ai
"https://paste.ee/p/aWhgy#jAV57fxsA3kd1YZplxTtru9zF50XN1CT" - this is the action class which is used often for enemy ai
ok surely we dont need to see every single one of these, when the question is just about converting invoke repeating to a coroutine 😅
You can make a bool check in update and if it's satisfied, run your logic.
No coroutines or invoke needed in this case.
i think im going to use coroutine anyway since the enemy will be waiting on other factors often so it doesnt use an action as fast as possiblr
Hello everyone does anyone of a way whete if I delete a unity project that it get completly deleted meaning that everything is gone including the scrips. Just to explain what Im trying to do im making a full platform game usually I like to name my scripts simple things like movement or health but when I delete the unity project so I can practice the platform again the scripts stay in the pc so anyone know how to make everything deleted when a project is deleted just so that I can save time instead of having to go after things and delete them one by one
the scripts are just files within your project folder. so if you delete the entire project folder, that includes deleting your scripts
this could just be a timer in update, or yea a coroutine with while(true) and a WaitForSeconds.
https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
You can do it in update as well. A coroutine might just look cleaner. It depends.
Hmm for some reason my scripts stay in the pc
how can you tell
the only thing left behind would be the temp files in ur %appdata% folder..
I search the name the visual studio script is still there
if u delete the folder where are ur files sticking around??
got any idea how to make the ai wait for the energy bar to be at the right amount to use the abilities required amount, but not stay locked on in case it needs to do something else then?
Visual studio
How are you opening the project in vs? It would be deleted together with the project.
i could easily make it wait till it's at the right energy before using it, but it would lock the enemy ai up from changing
are you perhaps using vs code and just leaving the files open? because then they would still be loaded in vs code until you close it (without saving them again)
If you can open it in VS, then you didn't delete anything
if u close VisualStudio.. and reopen it.. it wont find no scripts.. the .sln file won't be able to be found after the project folder is deleted
Ill try making a game again and close visual and come back to you guys
But thanks for the info
this is the file that keeps up with ur scripts names and whatnot..
it should also get deleted when the project folder is deleted
there is probably a lot of code id have to look through to even understand your setup. The basic idea would be that you have one central place where AI can choose their abilities. Then compare the current energy to how much an ability would take.
If you want to add features like waiting for a certain ability, even though it is able to use another then this is gonna be a lot more complicated and i probably cant help with that
What exactly do you mean by it being "locked"? You can run whatever logic you want whenever you want. Nothing needs to be locked.
it would wait to use the ability, but during that time it could die or need to do something else
Well, wait to use the ability, but don't stop the ai logic. It's as simple as that.
Hello people, I don't know if it is the corresponding channel (I hope so) but what is the best way to open a prefab door? I feel that when I rotate in Y the door is super narrow and looks weird hahaha. How do you do it? or the best way to do it.
probably by making it a child of a Transform and rotating that instead
It is an asset that in theory is already a parent object and inside it has the "frame" of the door and the door itself, what I am trying to rotate is the door, not the frame or everything. In that case what could I do? or some tutorial out there hahahaha
if you right click the door you can make an empty game object as a parent
and try rotating that
I am trying to implement a Platform type of obstacle. I want the player to be able to jump through it One Way. This was easy with the Platformer Effector. However when I hold the "jump key" the Player after passing the obstacle launches up again, as if it was jumping again. This happens because the Player gets in contact with the Platform which has a layer that lets the player jump. This is not what I want, as I want the Player to land, then be able to jump. The solution is simple, make the "jump input" false when the player presses it, however it isn't what I need. I also want the Player to hold jump to give a high jump. How can I solve this issue?
Code```cs
private void FixedUpdate() {
//Regular Jump
if (isGrounded && inputHandler.JumpTriggered) {
Jump();
}
// Make jump input false when falling
if (rb.velocity.y < 0.0f) {
inputHandler.JumpTriggered = false;
}
// Short Jump Logic
if (rb.velocity.y > 0.0f && !inputHandler.JumpTriggered) {
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * jumpCutMultiplier);
}
}
void Jump() {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}```
my enemy ai kinda works it actually attacks now 😱
as an idea, perhaps consider what it means to be "isGrounded" - if you're moving upwards, you're probably not grounded yet
That won't work, as I want the Player to be able to Hold Jump for a higher jump
from the code you've shown, and your description of the problem, it sounds like your isGrounded flag is being set to true and allowing a fresh jump to happen
I don't see what holding jump for a higher jump has to do with that
What solution do you have? @twilit pilot
as an idea, perhaps consider what it means to be "isGrounded" - if you're moving upwards, you're probably not grounded yet
I checked and yes, when I move upwards the Player is not grounded. However, when the Player goes through the Platform, it is then grounded. That is my issue
did you not write the code that decides when you're grounded?
In Update cs isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
yes, this is what you could consider changing so it properly matches your idea of what being grounded, and able to jump, actually means
as you've found this is going to be set to true if you're jumping through the platform
but why would you be grounded if you're still moving up?
how can you land on a surface if you're moving up?
an alternative could be to fix your inputs to differentiate between being pressed and being held, so regular jumps wont interfere with holding at all
@twilit pilot I found an easy solution, but am not sure if it may be dept for later. Anyways this is what I did cs if (isGrounded && rb.velocity.y < 1.0f) { jumps = 0; } Essentially I just needed to lock jumping with a variable, and every time you jump you add to this "jumps" variable. The jump code cannot jump if it already has "jumps" = 1. So this code above just checks if the Palyer is on the ground and the velocity in the Y axis is less than 1.
You helped me realize it was the isGrounded variable that caused this issue. Thank you! 
screen.resolutions``` allows u to get supported resolutions to the device itself
what about unsupported resolutions?
like if im using a mac or a PC, it will only pass landscape resolutions
but what about portrait one?
Why would you need the unsupported resolutions?
the games im going to make is a cross platform apps, it can be played on PC or on mac as well , not only for smartphones
but my team was asked to make the app being able to have "landscape" and "portrait" behaviour on mac/PC as well
we wont accept letting users to resize it, if they allow us to do i dont even need to bother with this
playing games on PC in portrait mode.. thats interesting
can you not just set whatever resolution you want? if its windowed mode especially
our current way is to "give a bunch of resolutions to users , and let them choose, whatever platform they wanna play"
thats it lol
little bit offtopic but it is also normal in those famous games right?
if u choose windowed mode, tho portrait simulation part is quite weird lmao
i havent really played a game that let me go portrait mode, probably cause a lot of the UI was designed around it being wider than it is taller
if you arent on windowed mode, its gonna look like complete ass
nah me neither, but that only worked on windowed mode
designing a game in general that works in both portrait and landscape would be a heck of a task from the get go..
so its still not too bad lol
unless the user like really wants this on the side of their screen, which most games handle by letting them resize as they want
which also is only available in windowed mode
i just gonna walk the old way
//portrait resolution : 3/4 (0.75) only , based on provided landscape resolutions, calculated only
//landscape resolution : 16/9 (1.7777...) only
if (1.76f <= ((float)r.width / (float)r.height) && ((float)r.width / (float)r.height) <= 1.78f)
{
int portraitHeight = Mathf.RoundToInt(r.width * 1.33333333f);
landscapeResolutions.Add(r);
if (GameManager.Instance.isLandscape)
{
newOptionData = new OptionData(GetResolutionText(r));
}
//calculate portrait resolution
Resolution generatedRes = new Resolution();
generatedRes.width = r.width;
generatedRes.height = portraitHeight;
portraitResolutions.Add(generatedRes);
if (!GameManager.Instance.isLandscape)
{
newOptionData = new OptionData(GetResolutionText(generatedRes));
}
}```
basically, in landscape mode, filter all non 16/9 resolutions
if in portrait mode, based on obtained 16/9 resolutions , calculate it to make it into a 3/4 resolution
An apple a day keeps the NullReferenceError away!
Is there any issue you're facing with this code?
Trying to find a bug in some complex combat logic for 2 days, found 7 other major bugs before finally finding the one I was looking for 😆
need help with code
can i paste code here
Describe what kind of help you need and paste your !code after reading the bot message below
📃 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.
📃 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.
... read the bot message.
small question
no errors
Yeah, but first format your code correctly or use a paste site.
definitely, use a paste site
```cs
Your code here
```
the if statement in the code execute all 5 kills together how can i prevent that
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Use else if and take a C# course if you didn't know about that
switch your if statements around. Highest killcount to lowest
Or that
Also all of these have a common bit, which is collision.gameObject.CompareTag("Enemy")
i used && so both of these conditions required
@zinc shuttle Pro tip. Whenever you find yourself writing code like that, with lots of copy/paste. It means you should be using an Array
Yes, but what I'm saying is that you can take it out into an outer if statement and put the rest inside