#π»βcode-beginner
1 messages Β· Page 370 of 1
Insignificant. Dont worry
i also want to have a way to clamp the rotation in a way
like once it rotates 180 degrees it stops
ill figure that one out tho
hmmm it doesnt remain in a circle
how could I make it so it rotates constantly without converging back? I need to use pi for that somehow but im not sure how
probably something to orbit right?
Someone?
Mornin'. im struggling with persistent data. can anyone point me to a tutorial that can help with player data being persistent across the game. like coins gems stats lvl inventory etc. ?
Do you want to know how to keep your data between scenes? How about between executions of your game? This recorded live session demonstrates how to do both. We will look at things like DontDestroyOnLoad, PlayerPrefs, and data serialization. Note that this tutorial is coding intensive. It is advisable that you understand datatypes and object-orie...
Thanks. I will take a look at them. @languid spire Sorry.
@languid spire nope, please no. Never ever use binary formatter, never, for anything. back then it was ok before the security risks weren't known yet
please dont suggest brackeys videos, they are horrible
Don't know about his videos in general but that specific tutorial should have been removed a long time ago
basically everything is complete hardcode, only designed to work for the purpose of the tutorial and cant really be extended by someone whos actually watching to learn. A lot of things just arent right as well
can't really disagree. I used to watch a lot of his tutorials but never followed any of them, just wanted to learn the concepts and implement things by myself
why are you suggesting BinnayrFormatter 
I think you will find that is Unity Learn doing that
and they definitely shouldn't. it's from 2014 so wasn't really a thing back then
but anyway, whichever method of serialization/deserialization is used the concepts are exactly the same
still
not a good tutorial to link to someone who's trying to learn
that tutorial should be removed by Unity
if by 'learn' you mean 'copy/paste', true
you are here long enough to know that most new people just copy/paste stuff from tutorials instead of actually learning ;p
indeed, and using Binary Formatter in a locally developed learning project has no security implications whatsoever
true, but I still see no reason to use it for anything, even JSON or something similar does pretty much the same without any real downsides besides human readable format
i am trying to rotate a part of a turret towards the target, but only on the y axis, but for some reason this code rotates it on all axis? (y and z are constantly 90) idk why, i am very confused
Vector3 D = target.position - transform.position;
Quaternion rot = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(D), verticalRotationSpeed * Time.deltaTime);
turretBarrel.localRotation = rot;
turretBarrel.eulerAngles = new Vector3(0, turretBarrel.eulerAngles.y, 0);
not sure why you are setting the euler angles at the end.
my turret rotation code looks like this
Vector3 target = Target.position;
target.y = Turret.position.y;
Vector3 targetDir = target - Turret.position;
singleStep = turretSpeed * Time.deltaTime;
Vector3 turretDir = Vector3.RotateTowards(Turret.forward, targetDir, singleStep, 0.0f);
Turret.rotation = Quaternion.LookRotation(turretDir);
this piece of code runs in an Update(). How do I make it so it doesn't go past the for loop until it has finished looping?
sort of like a roadblock for the update
i can only think of booleans but could there be a better way?
It doesn't go beyond the loop until it finishes
Ohhhh that clears up something. The way I check for input must be wrong as it still traverses the list
Are you perhaps wanting it to wait for each input in the loop?
You could use a coroutine and have a yield instruction that would wait till the particular key is pressed.
Thanks!
Pseudo code: for ... yield wait until (() => get key down) log ally namehttps://docs.unity3d.com/ScriptReference/WaitUntil.html
hm. i think the problem is that the part i want to rotate, is a child of another one, that's why it's not working, but WHY, why does this object rotate on all axis if i give this specific code for one axis, just because it's a child of it???
my turret is also a child, of the tank body. But look at your code and compare it to mine, your logic is flawed
it works 100% the same, i tested yours, it's not the code
which is even more confusing
then there is a problem with your model setup. you need to check that all of the forwards are set to the same
Tell me.
there is no VC on this server
[SerializeField] private Rigidbody2D rigidbody;
[SerializeField] private InputActions inputActions;
[SerializeField] private float movementSpeed;
private float movementInputX;
public void OnMove(InputAction.CallbackContext context)
{
Vector2 movementInput = inputActions.Player.Move.ReadValue<Vector2>();
movementInputX = movementInput.x;
}
private void FixedUpdate()
{
rigidbody.velocity = new Vector2(movementInputX * movementSpeed, rigidbody.velocity.y);
}
anyone know why it doesnt work??
i get this error
did you assign inputActions ?
i cant find the paramater in my inspector
i cant assign it
whats that?
is there a doc for it
is InputActions a class you made
Really
yes
show it
what is this supposed to show ?
this is the input actions and that is the generated class for it
if its the generated class you dont reference it in the inspector
oh i dont need to do that?
You create a new instance of it
new InputActions()?
also dont name assets with the same name
its the generated class for it tho, what am i supposed to name it
not the same name? doesnt matter where it came from
oh ok
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/ActionAssets.html#using-input-action-assets
has the instructions if u scroll down
thanks
not too sure if this is the correct place to ask this but i am on windows and i have other people working in linux and mac, but for some reason when they clone the repo Unity starts to throw errors becuase some libs are not loaded in, such as dotTween from demigiant and such, its weird because there is another person on windows like me and its fine for him to clone and do anything. any idea?
perhaps those libraries didn't get included in version control
the other person may have just gone and installed things from the asset store after cloning the repository
there's also the possibility that the assemblies for those assets have been set to windows only for some reason
bill gates strikes again
Why would you replace the code I've sent you with mine, if I have literally copypasted this code from the script you've sent to point it out?
The strangest thing for me is that you haven't even noticed the code is yours?
Sorry, I've been trying to get this to work for a while and didn't notice it was the same
pretty annoying
some libs get cloned fine whilst some dont but its weird that for a big lib such as https://assetstore.unity.com/packages/tools/animation/dotween-hotween-v2-27676 we are having this issue
i guess the only way to get around it is to create a package file which has these libs inside already as a wrapper, maybe that will work, i was thinking of writing custom editor scripts anyway so might just bundle all together
we've already told you the possible reasons for this issue, have you bothered checking any of them?
talking to me?
obviously yes, because these assets are just installed directly into your assets folder, they are not installed as packages. so there's nothing stopping them from being cloned correctly unless these files are not being commited to your vcs. or if they are only working on windows then that indicates that the assemblies are set to only include windows. all of this is something you can easily fix
Hey, I am trying to create a generic class but it gives me a message "no Monobehaviour scripts in the file, or their names don't match the file name". The message goes away as soon as I remove the type parameter. Can someone help?
right because you cannot specify a type parameter when adding it as a component via the editor. you need to inherit from the generic class in order to do so
so you could have a class like public class Foo : GenericSingleton<Foo> { } (you'll probably also want to constrain T to GenericSingleton type)
as an example, this is my singleton implementation. it is abstract because it isn't supposed to be attached as a component itself (not that it would work anyway since it is generic). behaviours that i have that are supposed to be singletons inherit from this
Well, consider first fixing the part I've pointed out
Hi Im trying to follow an old tutorial from Brackeys "MOVEMENT - Making an RPG in Unity (E01)" But in the newer versions I cant find this option, does someone know how to find this?
https://www.youtube.com/watch?v=S2mK6KFdv0I&list=PLPV2KyIb3jR4KLGCCAciWQ5qHudKtYeP7&index=2 (3:43)
Let's set up the environment! We'll also make the player move, and the camera follow him.
β Sebastian's channel: http://bit.ly/1O4svpW
β Download the Assets: http://bit.ly/2u4rcEX
β Download the Project: http://bit.ly/2uecCew
β€οΈ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·...
Anyone here use odin inspector? Should I consider getting even though I'm a beginner?
Newer versions of Unity use the AI Navigation package.
You no longer bake a navmesh for the entire scene. You add a NavMeshSurface to an object and then bake that
oh okay π thanks
I think the default settings for a NavMeshSurface just grab all level geometry, so it'll match how the old scene-wide bake worked
sry but do you know how to install the package too? π https://docs.unity3d.com/2021.2/Documentation/Manual/upm-ui-quick.html the instructions on that website are not very up to date I guess...
what version of unity are you using?
bc its an older project
do you think that might be the problem?
a version that old will still have the scene-wide Bake option
show me your Navigation window
if you can't find that; it's just Window > AI > Navigation
Oh xD tysm thats what I was looking for
I just didnt see that I had to click on "AI" first. aaah
Hi, need help with List<GameObject>.
Cant show code rn...
Im making mid play savjng to let player continue playing if he exit, just simple data (pos of object and some script stuff)
All objects are in list, but when i try to save list while player is doing smth it says that collection was modified..
i tried using try/catch, and restart saving corotine, but it stops itself if i use StopCorotine()...
What should i do? I also tried to save data from objects and then pass it to saving script, didnt help, same error but in passing method...
The error means you are modifying the collection whilst iterating it.
Don't add/remove things from the list while it is in a foreach or another loop
The enumerable underneath assumes the collection is the same.
If you need to modify data, use a separate collection and replace the list with that one instead when you are done
Basicly create a second list and replace it once the loop is over
List stores GameObject, i tried storing script too, but Object/Script can be destroyed mid saving, which will lead to same error
So don't destroy it
Or make a list with only the relevant content to save
Either way don't modify the content
You cannot modify a list inside of a foreach over it.
the only way to fix that i see is setting time to 0 and stop whole game for half second to save... which is not better idea
you'll need to use an indexed for loop and manually change the iterator if you change the list
@ whoever deleted that question just now
Quaternion.identity is the Quaternion representing the default orientation
i know i deleted it because i decided to go to the docs instead of wasting your time
thanks
good call
Okay, thanks y'all who responded, ill try to do what ya said. 
I have a gameobject that has an animation with keyframes that change alpha, how come when I change the alpha of the spriterenderer in inspector or in code, it doesn't apply?
show code
Does anybody know why the enemy Car dosent move an floats?
actually wait, if you have an animation that controls the color then that will override any code you use for it
looks like its collider has a big cylinder?
@lethal bolt it looks as though you have a big cylinder collider, so it's using that to 'place' it.
whats the difference between a list and a linkedList
Yes............
Okay well the bottom of that collider needs to be 'inline' with the bottom (wheels) of the van, that should move it to the road surface.
is that a NavMeshAgent on the truck?
Yes
What is that collider used for?
the truck model appears to be positioned above the object with the agent on it
I fixed Collider
this is a linked list: https://en.wikipedia.org/wiki/Linked_list
and a List<T> is basically just a resizable array (it's literally just backed by an array)
But he just rotates around
linked lists do not provide efficient random access
but they do provide efficient insertion and removal
Yeah, even if there are no transitions to it
the animator sets all animated properties in-between Update and LateUpdate
Okay, next thing, how are you moving the van? (movement script etc)
this includes every property animated by any state
you can't make it stop writing by just leaving the state whose clip sets the alpha
Why not search for a Stack Overflow question with over 450 up votes?
if the animation is active then it will control that property. if it is not then you need to show your code so we can understand why it isn't setting the values you are expecting to be changed
If you want to overwrite what the animator does, you can do it in LateUpdate.
it doesn't matter if you aren't in the state that controls the property, or even if you've never been to the state!
Okay there's nothing there that's actually moving it, just giving it a target. Can you show you NavMeshAgent settings please?
Oh wait, sorry, misread. Can you show the 'Enemy' script please?
okay, sorry 1 sec, looking at a few things at the same time. lol.
lol
Okay so is it pointing at the 'target' correctly?
List is better unless you need to apply content in between elements, then a LinkedList works better
Considering you usually don't add content in between, you should probably just stick to Lists
Yes. Until i collide with it
Also, I believe a LinkedList is bad when it comes to accessing data randomly. It uses a different system whereas a list is a basic array underneath
So it takes longer to do that
Okay, are you sure that your NavMesh is being generated properly? (press play, pause the game and then look at the scene view to see if the 'roads' have a blue overlay?
I think so?
Hmmm......okay, it looks like it's being generated a little 'high' (intersecting the wheels), try moving your van 'up' quite a bit so it starts 'above' the navmesh plane (it should snap back down when you press play)
Yes i moved the car up an the navmesh down and it works! THANKS !
you can change animation set values in lateupdate
Awesome. No probs. Yeah anything that goes onto a nav mesh has to be able to 'look down' and see the navmesh, so if it's a little low it won't see it. Surprised it didn't throw an error if honest.
thank you!
In a pokemon style game where there is grass you can encounter enemy pokemon is it better to put the CheckEncounter function in the player movement script or on a grass script itself?
You check what kind of tile you're on and you act on that. That should be the responsibility of the player, not the grass.
It would depend on your game but if you're using a grid then maybe you can simply evaluate whatever you're wanting to when you enter that tile.
Great responses, much appreciated
I'm not using a grid based movement so I'll stick to keeping it in the player controller
I'm setting direction in the Update function yet it calls it over and over again as expected, what's a way to avoid this so as soon as Direction is set it just sets it once?
SetDirection(movement);
Debug.Log(direction);
}
private void SetDirection(Vector2 movement)
{
if (movement.x == 0 && movement.y == 1)
{
direction = "Up";
}
if (movement.x == 0 && movement.y == -1)
{
direction = "Down";
}
if (movement.x == 1 && movement.y == 0)
{
direction = "Right";
}
if (movement.x == -1 && movement.y == 0)
{
direction = "Left";
}
}
i'd like to suggest you use an enum for the direction rather than strings. you'll have compile time checking for things like misspellings instead of relying on you remembering how you spelled something since capitalization actually matters when it comes to comparing strings
Okay thank you I'll rewrite that
Only set your direction (call the function) if a move was made.
Just letting you know that it is not good choice to compare equality (==) for floats (Vector2 components)
whats the difference between this and just a normal equals?
that is creating a get-only property
i see
That's not a math operation you've got there
What's the better decision?
I tried to make some improvements to the code, but the fact that the fireballs don't disappear as I would like when they touch the ground or the player (they don't disappear at all) without any kind of explicit error remained
Something ranged for example. if (movement.x > 0.9f && Mathf.Abs(movement.y) < 0.1f)
Your OnTriggerEnter2D method tells it should disappear when the collision's layer is Player, or tag is Ground and the prefabName is not fireballPrefab2
Have you even tried check whether it's called? It's not going to be called since your Collider2D has its isTrigger disabled
- The
OnTriggerEnter2Dmethod happens for the object if it has itsisTriggerenabled. - The
OnCollisionEnter2Dmethod happens for the object if it has itsisTriggerdisabled. - In both cases, the
Rigidbody2Dmust be added to the object with the method. - The collider it collides with must also have a
Collider2D - The
isTriggerof the collider it's supposed to collide is doesn't matter.
I'm not sure I like how enums default to a value, for example when I am setting player direction it defaults to left even though input has not been received yet. Technically it should be null if I am understanding my own code correctly. Should I have it default to down? SInce the player is positioned that way at the start?
create a None member for the enum, or whatever you want as the default should be the first member
then just set a Unknown as your first entry of the enum
also enums are value types so they are never null
Ohh thank you so much
How do i install Visual Studio Code IDE?
I mean a sprite is normally facing down by default
Vsc is not an ide
You may visit the visual studio code website to get the installer which lets you get visual studio code
!vscode
I mean the thing that shows the herrors
Already did that years ago and still doesn't work
did it like 4 times
The IDE stopped working too
and my pc doesn't support it
It's not an IDE
Years ago? You can do it one more time now
With years ago i mean like i did it since a lot ago and keep doing it but never worked
Have you been coding with no errors showing up all this time?
Hard core mode
Yeah
I sincerely respect you
What version of Unity do you have?
It's not supported by 2020
Have you installed the extension?
So then you should definitely do it again. "Years ago" is an eternity in software terms
if you cannot figure out how to get vs code configured using the guide the bot posted, then you should consider just switching to visual studio. it's just as easy to configure, but with less steps that are easily fucked up or forgotten. and it also is less likely to just stop working
Yeah
The packages and plugins have definitely changed since then
Visual studio stopped working
at least for me
and it goes to like 1 fps
Follow the guides once more, you can only try - as mentioned, things have changed with VSC.
Could you show your Package Manager?
Am opening the project
How do you all feel about this gray area autocomplete that I think is relatively new? Invaluable? Fools gold?
I don't think it's new
that's intellicode. it can be helpful sometimes, but it's also annoying just as often
Do any of you turn it off?
oh yeah, i think its like 2 years old or something
i have turned it off because of how often it just gets in the way
I tend to just hit escape if it's suggesting something dumb
I probably tab about as often as I escape so it's fair to leave on
i dont think the specific unity API helps it much
what's your computer specs even
if vs is lagging because your pc doesn't have the power then it'll be very hard to use unity
I only know i have 8GB Ram and GT 1030
that shld work fine tbh, more ram would be appreciated but nonetheless
watch the number of tabs you have
why does everyone always throw their GPU info out when that info is entirely irrelevant
your GPU is not going to impact the speed of your IDE in any meaningful way
That's their point
ram is pretty important, with just OS and chrome on the 8gb is completely gone
right, i never said the CPU wouldn't. my point was about them providing their GPU info
yeah, thats irrelevant
yes and that was the entire point of what i was saying
Because GPU manufacturers have successfully gaslit people into thinking that GPU versions are akin to console generations and saying you have a "1030" is equivalent to saying like "It's a PS5"
So you have people with some beastly 1400 dollar graphics card and then they have like, an i3
and then they blame bad performance on their graphics cards. I know what people you are talking about...
guys why does notepad take 6 years to open this 1.3gb file? i have a RTX 3090 and a billion gigs of ram!
nevermind the fact i'm running an intel core 2 duo and have a 5 rpm hard drive
The system can only go as fast as its slowest part
the CPU relies on RAM, the GPU relies on the CPU and the VRAM that's inside the GPU body, etc, etc
!vscode
this is a code channel. #β°οΈβterrain-3d would be more appropriate for that question
Why everyone ignores people when they submit this error?
when i search it no one of the people who have reported it get even answered
go to the output to see more details and maybe an actual error code or something that you can search for
It's not useful
oh okay
Because it's pretty self explanatory - it couldn't connect to the language server
You got internet? Behind a firewall? VPN?
I have ethernet
Any number of things could prevent your network from connecting to one specific endpoint instead of another
And we can't really know what your connection setup is like
No VPN
How could i know that?
Normally you'd know what kind of software your own computer is running
wdym with that?
Like software like OS?
Just to make sure everything's up to date, did you do all of the steps in #π»βcode-beginner message ?
Yeah i did...
Can you show your Unity package manager?
It's all what yall say "just do the steps that the bot says" i did them million times
Visual Studio Editor package is installe
Because they work
But they dint for me
Your problems seem to stem from either:
A) Faulty hardware causing installations to fail
B) Software blocking connection to the language server
There may be a conflicting package, thus why I've asked
Sorry to interupt this editor thing but I have this issue where the player "walks" through the door (scene change), and then upon exiting to go back to the world their position has changed. Would the best approach be to store the position where player has walked and then re-position them accordingly on the second walk through to the world? Here's a gif to illustrate if my message was unclear
Are you loading scenes?
If you have each "exit" have a paired entrance tile on the new scene, you can keep track of the last exit you used, and spawn the player at that corresponding "entrance" tile on the new one
Yeah SceneManager.LoadScene(scene);
You know any way to make the faulty hardware to fail or any software not block it?
So, you'd be able to see "The player's last exit is null" and put them in the middle, or "the player's last exit was house_front_door so find the tile marked house_front_door and place them there
yeah that would allow having multiple entrances/exits quite easily compared to just storing the last overworld position
that may be a problem if there are multiple exits, so maybe just best to link exit one door to another
If it's A, you'll need to diagnose what specifically is failing and replace it (it sounds like storage but it could be system board or CPU as well). For B, you just need to find whatever software you have that can limit connections and disable it
Can you still simply provide an image of your package manager?
yeah sure
could probably just do some gamemanager with a list of entrance/exit
Isn't the simplest solution the one I proposed where we store the position at the point of walking and position them when exiting?
What would happen if you've got multiple entrances?
OH like a dungeon
Further expanding on that, what if you were to re-enter from a different entrance?
There's only one door in my head, how would there be a different entrance?
sure for now you only have one door. what if later on you decide to add buildings with two doors though? those absolutely exist in pokemon
Supposed the village was an entire scene. If you leave north but return from the south, what would happen?
They would reppear north
is there a time.Time for when you load the scene?
Nope, how is that necessary?
did you look at the docs?
Or if you teleported and exited a poke center, should you use your last position.
@slender nymph docs for what?
Ahh
not you, the person whose question appears right before my response
Theres something i dont want to run for the first half second since the scene has loaded
Oh this is for your game, not mine π
also yes that does exist. hence why i suggested looking at the docs
So if you entered a bug forest from the south entrance and exited towards the north entrance. Keeping track of your last position in the particular scene would have you teleported back to the bottom entrance.
Sorry I'll look at the documentation when I get the chance. but I'm still not sure how that relates to my scene loader
again, the suggestion for looking at the docs was not for you
Oh you tagged me so I was confused once again
i tagged you to say that your response of "no" when someone else asked if there was a time since scene load was incorrect
This message did not tag you
#π»βcode-beginner message
what just happened? I tried one of the errors i had solution i found on a reddit post and now this happens
and it loads normal visual studio
Thanks everyone for the suggestions, I'm going to review these messages and take notes on the better implmentation
You need to remove the VSC Editor package if you're following the new VSC setup
Note: The Visual Studio Code Editor package published by Unity is a legacy package from Unity that is not maintained anymore.
I cant remove it because other package or dependency depends of it
it's the engineering package group, just unlock that or whatever
It's a common conflicting package that should be removed.
I want to make the Wheels rotate 30 to the rigth an 30 to the left but now they just spin in circles and i know the problem but i dont know the sulotion and i couldnt find it
Have a class variable that maintains the rotation and add/evaluate/compute using that variable.
oh
For instance, you'd be able to clamp the value.
If you want to change the rotation by an amount, use .Rotate
right now you're setting it to a specific value
(β―Β°β‘Β°)β―οΈ΅ β»ββ»
like Dalphat said, you also need to clamp the value between -30 and 30, and after that you can just rotate it
Woooooo (β―Β°β‘Β°)β―οΈ΅ β»ββ»
So I know I'm not doing this in the suggested manner but I figured I would do it simple first then smart later but here's my teleported function. For some reason the player is not being "put back" in the same spot as where they teleported from. Any insights?
private void OnTriggerEnter2D(Collider2D other)
{
SceneManager.LoadScene(sceneToLoad);
// We are storing the last position and name to be used later when we re-teleport back outside
lastPos = player.transform.position;
Debug.Log("lastPos" + lastPos);
hiraganaScene = SceneManager.GetActiveScene().name;
// If scene is equal to HiraganaScene then we telepot back to HiraganaScene in the position described
if (hiraganaScene == "HiraganaScene")
{
player.transform.position = lastPos;
}
}
well are you preserving the object/position between scene changes?
Did you save last position?
Does lastPos not do the trick?
you have to store it so the value isnt wiped
Oh the value is not persistent?
maybe start with PlayerPrefs or DDOL
When the scene changes all objects in the previous scene are destroyed, along with their data.
I see, what and what is meant by PlayerPrefs or DDOL are these persistent data storage to be used game wide?
unless you add the attribute DontDestroyOnLoad
PlayerPrefs is a simple storing system unity has built in
DDOL is not storage, its a DontDestroyOnLoad function you can add your object to a special scene that never gets destroyed between scene changes (this will require good system to pass references though or singleton)
Player pref and json are means of writing data to disk.
using file system to store is overkill, static is enough in your case unless you expect player close your game and reopen it after switching the scene
PlayerPrefs seems like something I would need later on down the road when I want to save player states, right? I feel like I just need a static object like @gaunt ice is describing
they are also used for persistent scene 2 scene data
~~He may need a state manager for different scenes etc but maybe that's too much for now ~~
@gaunt ice I guess static could work but its a Noob trap
"noob trap" π
yes next thing you know you start making everything static π
"this is soo much faster"
why isn't everyone doing this
or just copy everything to the system clipboard
(I'm joking btw)
This guy lol
"I'm the greatest!"
"Oh no!"
Okay I'm going to use static for now, but I appreciate you all pointing me all in the right direction for the future.
"the power of static, in the palm of my hand"
one other thing about this that hasn't been mentioned yet is that your new scene hasn't actually loaded yet. it doesn't load until the next frame
What does that translate to in my game? The new scene is definitely still loading just not the position being changed.
i never said it isn't loading at all. but it has not loaded by the time that code you are using to assign the position has run. because the scene load does not happen until the next frame
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior
can cause frame stuttering andcan be confusing because load does not complete immediately.
Oh I see, so in a noobie nutshell the scene is asynchronous and not matching up with the frames. Therefore it can cause "frame stuttering" as described. What is the solution to this?
no that is not at all what i'm saying. that part of the description is irrelevant
there, i edited the quote, ignore what is crossed out and read it again
Maybe have your player in the new scene update it's own position or something from the new scene update the player's position
So are you saying that my lastPos is going to be effected by this async behavior?
oh my god, all i am saying is that all of that code in the method after the LoadScene call is still happening in the same scene because the scene has not changed yet
Oh my god now I understand
So even if I fix the issue with static it still won't load position correctly because the aforementioned code is happening at the previous scene
yes, but if you just let the player in the new scene assign its position from that saved position then it will be prefectly fine
So are you telling me to put lastPos = player.transform.position in my next scene?
Reminder that static data persists between scenes (everything really) - they belong to the class and not instances of the class.
private void OnTriggerEnter2D(Collider2D other)
{
SceneManager.LoadScene(sceneToLoad);
// We are storing the last position and name to be used later when we re-teleport back outside
lastPos = player.transform.position; <-this line
Debug.Log("lastPos" + lastPos);
//some codes
}
no, just the last bit where you assign the position to the player
I am so confused because I am "cheating" by doing the ghetto trick of checking for the Scene Name and then assigning player.transform.position = lastPos; which as I understand will just change the position of the player once they are in our HiraganaScene
remember how i already told you that the scene has not changed by the time you check the scene name?
Let me draw this out with crayons and I'll get back to you
i thought you'd finally understood it here ^
I do not lol
queried scene change
lastPos=player.transform.position;
if(some bool that is probably false){
player.transform.position=lastPos;
}
Ive stated a new project and i got stuck on rotation and Quaternion. Camera has a like topographical view on the player and the camera follows an object that is a child of the player. The issue is that i wanted the player obj to rotate towards towards the cursor.My idea of doing that was by sending the ray from the camer thro the cursor (variable "pozicijaMisaUSvijetu") and then initiating one vektor towards the point of the the contact i got from the RayCast (hitInfo) and one from the playerObj forward. Trom then on calculating the angle diffrence between them and setting the obj rotation with quaternion slerp.
Player curently spins not around his own axi, he on the axi around some unkown point
Peice of the code responsible for this:
void fun_rotacijaIgracaPremaMisu()
{
Vector2 movment = new Vector2(horizontal_Input,vertical_Input);
movment.Normalize();
Ray pozicijaMisaUSvijetu = Camera.main.ScreenPointToRay(pozicija_Misa);
if (Physics.Raycast(pozicijaMisaUSvijetu,out RaycastHit hitInfo))
{
Vector3 vektorDoPozicijePresjeka= transform.position - hitInfo.point;
Vector3 usmjerenostIgraΔa = transform.position + Vector3.forward;
Debug.DrawLine(transform.position, usmjerenostIgraΔa,Color.red);
Quaternion test1 = Quaternion.Euler(0,MathF.Atan2(vektorDoPozicijePresjeka.y,usmjerenostIgraΔa.y) * Mathf.Rad2Deg,0);
transform.rotation = Quaternion.Slerp(transform.rotation, test1,0.5f);
}
}
Screenshot shows the POV of the camera (player shuld be in the middle of the screen)
PlayerObj has the script attached to it and has rigidbody
Player(Child of PlayerObj) is the capsule and has a box collider
yo
ok so small question i'm trying to do an if(lookingDirectionInput > new Vector2(0,0)) it do something, they are both Vector2 value but only problem if statement don't suport "<" with vector2 for some reason! any idea how i can go around this?
i don't want to use == cause i'm gonna do some other things with it and == wouldn't work
< Vector doesn't really make sense
Which part do you want to check is bigger?
The magnitude, x component, or y component?
Pick the one you want to check and use that
what do you think that is supposed to do? because it doesn't make a whole lot of sense to compare which Vector2 is bigger
ok wait no i think i have an idea on how i can fix this thank you dude
when i setpositions for linerenderer is there any significant performance difference if i use array of 2 vectors vs 1000 vectors
use the profiler if you have performance concerns
we already confirmed that profiler lies
i don't know who "we" is, but what would make you think it lies?
1 performance on pc is completely different than on phone
2 pc has lots of random garbage that doesnt occur on phone as well
Actually I'm like 100% sure we proved the entirely opposite
phone has their own profilers too
esp iOS has a good one
So then profile it on the phone?
what about no
phone debugging is bad
i just wanted to know if theres difference
everybody start mashing "try it yourself"
i dont wish to code for next week just for answer
yes no much better to ask random people on discord arbitrary performance values
Do people usually do unit testing or other testing for unity?
Just give them an arbitrary answer so they go away for another few days
Then continue to suffer the burden of not knowing
No there is no significant difference. See ya.
I've never been a fan of unit tests but I do pretty regularly set up "mock players" to feed a specified set of inputs to replicate specific behaviors. Kind of like making a TAS for bugs
dang nav, should've kept your answer up so that they could have chosen their favorite of the two
Unit testing is useful but afaik is not very common in Unity games
(but unity does have decent tool for it)
That doesn't mean the profiler lies in the least. The profiler tells you the truth for the place you are profiling. Just profile your phone, and it will also tell you the truth for that device
Ah, dang lag.
Just not very common in Indie dev games at all. It's truly hard to test a game, when half the bugs come from unique cases that the dev will never think of.
Am I reading this correctly? When I enter the house despite the scene changing to House001 it actually enters the if statement anyways at the moment the player collides. Is this the asynchronous behavior we were talking about?
very true. So many potential things that can wrong in a game than a traditional app, yea throw physics in there too , very difficult to predict every potential problem
again LoadScene does not actually load the scene until the next frame
and the frame will not end in the middle of a method
Yea imo it's not even worth doing especially alone. It seems to get mentioned every so often, but I'd love to see how many big games even do it. Dev's at jagex (old school runescape) have even said theres no reason for them to unit test after many suggested it because of the amount of bugs in game.
The only thing I'd consider making tests for is like my item system to ensure formulas are correct. Other than that, if I made a mistake somewhere then it's likely not noticeable
just seems like a lot of work most of the time with very little gain
I wrote an editor extension that turns off graphics and increases the timescale to simulate, say, 10FPS gameplay at a much higher speed
then i let the game run for a while and see if anything errored out
as well as if I've got obvious leaks/performance drops
I also write editor extensions to scan for things like missing references (after annotating fields that are allowed to be null)
yea its handy for me sometimes when I wanted to test the CommandPattern or something more predictable like grid movements
This is very helpful for updating existing prefabs after I change how something works
(something I'm trying to do less and less as I start adding content, but...you know)
As many things do, it probably comes from the people with web dev backgrounds or in similar environments. Code testing even plagues other fields, where they want 100% coverage which is 99% useless.
one thing I do need to do is better test weird filesystem problems
I don't know how people get some of these errors...
That's pretty smart, I'll probably do something similar
I've heard of this being called "soak testing" before
Can't find too many people talking about the idea
Punch Out!! on the Wii has a mode where it just plays the entire game automatically
(with cheats enabled so it doesn't have to play well)
that's an amazing game
it seems very well put together
IIRC you couldn't save so you had to beat the whole thing in one go
Oh right
i guess i should just assume that no file exists, even if I just created the file, and that no file has non-garbage content
005-737-5421 to get to Tyson, IIRC
I think when I was a kid I didn't know the password system and just played it through till I got it
ahh passcode checkpoints/saves. Dark times
hey guys can i get some quick help
maybe
if you ask a question, perhaps!
don't cross post; you already posted in #archived-code-general
yeah i was about to say if you can go there lol
that problem is also not a code problem
ask it in #π»βunity-talk and show what you are doing
Alright... so I think I'm getting a bit warmer here but the player is still refusing to move back to the same spot. Am I still not taking into account for the async scene loading?
private void OnTriggerEnter2D(Collider2D other)
{
SceneManager.LoadScene(sceneToLoad);
// This scene is set to the current scene
thisScene = SceneManager.GetActiveScene().name;
// We check this scene for HiraganaScene in order to set the lastPos
if (thisScene == "HiraganaScene")
{
lastPos = player.transform.position;
}
// If we have entered the house then we set hasEntered to true
if (thisScene == "House001")
{
hasEntered = true;
}
// If we are in the HiraganaScene AND we have previously entered the house then we set player position
if (thisScene == "HiraganaScene" && hasEntered == true)
{
player.transform.position = lastPos;
}
}
imo you're overcomplicated the shit out of this
make your House an actual object that stores its Entrance point as a Trasform/Vector3.
then you just lookup the coordinate from that object
public class Building : MonoBehaviour{
public Transform entrancePoint;
}```
Which part even is async here? Nothing here seems to be waiting for anything
they latched onto the phrase "semi-asynchronous behavior" from the LoadScene docs that talks about how LoadScene does not actually load the scene until the next phrase
so they are ignoring everything about how the rest of the code in that method is running in the same scene still despite having been told several times that the new scene has not loaded yet
Oh I think I'm starting to get it... thisScene is the previous scene... right?
So when I teleport the first time, thisScene is still Hiragana001 and then when I teleport out of the house thisScene is House001
using scene names for this is horrid
yes, because nothing happens until the end of the frame
Jesus that was hard for me to comprehend lol
here, hopefully this spells it out for you https://hastebin.com/share/ehojoyerel.cs
Huh? It's blank lol
man fuck hastebin that's the least intuitive share site
at least changing the extension can fix the syntax highlighting though
Okay after a short review I see what you're literally drawing with crayons fo rme lol
ever since topal changed it went to shit
I like GDL Space
yeah I liked it to the point I've made a .NET version of it as pet project
maybe we can use it some day π
This code is giving an error that line 19 "type or namespace spike can't be found." Spike is another script that will be on the prefab instantiated on the line above. I've done this tons of times with other scripts and components so I'm not sure why it's not working in this instance specifically.
https://pastebin.com/1xArQD16
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.
are you sure you have a script called Spike?
double check the script name and class name
You simply don't have another script called Spike πΈ
Or it's in a namespace or another assembly.
also is the error underlining inside the code editor ? make sure that is also configured
wow I just didn't rename it correctly, oops. Thank you!
So for my player to change position back to the correct spot is this the correct logic to implement? Rather than my previous approach of trying to actively set the positions and create a lot of confusion for myself.
* When the player enters the new scene, set their position using the scenePos
Basically set the tile position for the entrances and then manually set those positions based on where the player enters and exits
you should keep a collection of entrances and exits so that each entrance can reference some exit so you can always get the correct position from the exit point
yeah, you should try to make this a little more...structured
you won't need to care about the player's previous position, you just need to know what entrance they are going through so that they go to the correct exit point
Right right, thank you for the insights
I used ScriptableObjects for this kind of thing
each save point got a SO that had its name and its position
(i copied the actual position of the save point into the SO with a script, but you can just set it manually)
for "paths", like going through a door, you'd have a pair of SOs that reference each other
I see, I've used scriptable objects before but I'm still a bit unconfident with them. I'll definitely try it out with this use case though
π₯²
the minor X-factor here is that you need to know which entrance to use
That's pretty similar to what we're discussing, right? Store the point as an object and then use that point to teleport
pretty much
As you can tell I'm a slow learner π
much easier if the buildings track their own points
less stuff for your player code to worry about
That is why I'm a fan of the idea of having an "entrance" object.
When you go through a scene transition, you would store the entrance you used in the game controller (a singleton). After the new scene loads, you'd ask that object for the corresponding entrance in the new scene.
[CreateAssetMenu]
public class Entrance : ScriptableObject {
public Entrance otherSide;
public SceneField otherScene;
public Vector3 position;
}
You could put the destination scene in there too
Right right I am starting to see your points
Each doorway would have an Entrance reference
and each Entrance would reference another Entrance
Thanks for the sage advice all, much appreciated
OOP πͺ
and, tbh, you could totally just use FindObjectsByType to find every single door in the new scene and figure out which one matches up with the otherSide field of the entrance you used
instead of storing a position to take you to
it's not the end of the world
i mean . . . it's getting there . . .
how can I watch for hits on my 3d mesh object?
depends , what do you mean by "watching for hits"
what are you trying to do
I mean
I want my mesh to be "Clickable" using OnMouseUpAsButton
but it does not really work
when I click nothing happens
which method did you use
only one method works built in on MB that use collider
yeah..it works now
i forgot to add a collider
thanks π
I made it so that when the mouse hovers over The object the script is applied to it scales up a little and returns to original size after the mouse exits the collider area im just wondering how i can add range? ex: 5 meters away not interactable 1 meter away interactable.
!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.
Quite the opposite in fact.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Woopsie
If you want to increase the area OnMouseEnter detects, you'll need to increase the area of the collider
Oh sorry I left out that itβs just infinite ranged I just want to know if thereβs anyway I can make a limiter on range somehow unless increasing the collider is the way
Oh, distance from the camera? You won't get that with OnMouseEnter. You'll need to use Raycasting.
https://docs.unity3d.com/Manual/CameraRays.html
Thank you I will follow the rules if I come back
How do I instantiate a UI GameObject as a child of a canvas? Normal Instantiate is not working.
not working how?
whats wrong
it wont take my canvas reference as a argument in the Instantiate function.
oh man
I should learn how to read, i fixed it
Instantiate(prefab, canvas.transform) is how, right?
That would create your prefab as a child of the canvas
yeah I was trying to pass just canvas rather than canvas.transform for some reason
currently, the way this script works is by checking if a timer has reached its intended value allows the player to click a bar. during the timer trying to reach it's intended value, this bar fills up based on the timers current time and the max time. how can i reverse this so that the timer starts and the bar starts to fill up only after the player has clicked?
this is my script:
https://hatebin.com/sjtdhyygvp
Easiest way is to just flip a bool when your user does an Input.MouseDown or w/e input you're using so that for each sequential update will now go into that section of code.
The idea is already on that code, just gotta move the bool logic around.
Anyone know a cool tutorial to learn hitboxes/hurtboxes for a 3D action game?
Please ping me if so ty
this sounds dumb but i forgot Input.MouseDown even existed ππ thank you though
What do you need a tutorial for? Hitboxes are just colliders.
I'm aware of that, but since I'm pretty new I would like to have a tutorial to learn about it more
This is the beginner channel so I thought it'd be a given that I don't know much atm
We generally don't just suggest tutorials, since you can search that yourself.
If you have a specific question or concern, we would be happy to explain and help though
You can use as many as you want and flip them on and off at will
Got it. Thanks
Oh my gosh, for those who were helping me out before. Thank you. The player now correctly goes back to the desired position when exiting the door. Celebrate good times
You should make a #1180170818983051344
It's been cool seeing your progress so far, but I probably missed some of it
On it!
Does anyone know where to find the "NavMeshSurface" component? I only see NavMeshAgent and NavMeshObstacle
Do you have the Ai navigation package installed?
Like under package manager unity registry?
Yes
I dont see it as an option
What version of unity are you using
How do i check?
look at your appbar?
3.5.1
thats hub
you have to add package by name
Is it just "AI"?
You may also want to consider updating to the latest patch for that version, you're missing like 2 years of bug fixes and stuff
under Packages: Built-In
true
This one though?
no, that's the older built in stuff that the AI Navigation package was improving upon. i'm also fairly certain that the navmesh surface component was introduced in the AI Navigation package as part of the new work flow
Gotcha so I have to update unity itself
well you should update. but you can just install the AI Navigation package by name. a simple google search will tell you how to do so
Oh gotcha
So is it technically 3rd party or just not autobuilt in but still provided by unity?
it was just experimental still in the version you are using so it was not visible in the package manager
you update the editor with the hub, not through that menu
updating requires downloading the newer version
I guess I dont have the editor downloaded somehow
But I guess I'll download Unity 6 preview
yes, this is the window you use to select which version of the editor you would like to install. if you just want to update to the latest patch then get the 2021.3 version listed right there
i do not recommend migrating an in-progress project from 2021 to unity 6, you may run into a few issues with API that has changed as well as a few other features that have changed
Gotcha I just started it so no trouble to reset
So is the editor where I actually make the game? Sorry if this sounds stupid but right now I know the hub and unity itself is the editor the same or different?
"unity itself" is the editor. it's literally called the unity editor
Ok gotcha so 2022.3.31 is the most recent patch? There's no 2023 or 2024 patch?
2022.3.31 is the most recent patch for the 2022 LTS release, yes. Unity 6 is the version that was 2023 but was renamed as they are moving away from the slightly confusing year naming scheme
Gotcha, do you know why it reccomended 2022 and not unity6 then? because its a preview?
yes, 2022 is the most recent LTS version where LTS stands for Long Term Support. in other words that version is going to receive patches for about 2 years (we're a bit more than a year into that cycle). unity 6 preview is the preview version before it becomes an LTS version, when it becomes LTS later this year it will likely receive the (Recommended) marking in the hub
Gotcha thank you so much this was insanely helpful. I guess one more question, what do you recommend for current projects when Unity 6 becomes LTS?
it's usually best to just stick with the latest LTS unless you need specific features from a different version or i guess don't want to be beholden to the pricing update that comes with using unity 6
hi guys can someone explain to me:
myBool = !myBool;
im not sure why its needed in a code for say a toggle switch
it assigns myBool to the opposite of itself
That makes sense thanks again
for this, you have to understand the ! operator . . .
so confused by this phrase itself
! is the "not" operator. if myBool is true then myBool = !myBool; assigns it to false
so if myBool is true, then myBool = !myBool is saying "myBool is assigned to not true"
does this mean that if I dont put this in the code, once I toggle something to false, it will stay false?
no because the next time it would then say "myBool is assigned to not false"
and what is the opposite of false?
If you are setting it to false, then yes it will set to false
myBool = myBool will do nothing.
It would be setting it to whatever state it already is
in layman's terms, ! will negate the value . . .
if you set it to false, it will be false . . .
oh i misread that, if you do not include this line then the value is not going to be toggled to the other state
Instead of saying (if bool = false, set bool = true) and (if bool = true, set bool = false) you can say bool != bool for the same result
oooooooooooooooooooooo
very silly question but is there a way i can hide most of these projects in my solution without actually removing them?
probably not. although you don't really need most of those projects loaded so you can just delete the csproj file for them
doing so should speed up your load time for visual studio too
hey would anyone be willing to give some 1-1 lessons about making a first person character?
im kinda new to this whole coding thing and i cant find any good tutorials
How much are you paying?
Private tutoring is not cheap
if you are looking for a tutor, you should look on a reputable site where you can hire one. you are incredibly unlikely to find someone here who is willing to privately tutor you for free.
there are also dozens, if not hundreds of tutorials on that topic. and if they are too advanced for you, then start with the beginner courses pinned in this channel
idk how much i have yet i dont get payed till friday
ight
thx
So I'm writing a collision with the grass for random encounters in Pokemon yet I don't know how to call the Collider2D of the LongGrass, how would I go about calling that collider to be checked for collision?
private void CheckForEncounters()
{
battleTimer += Time.deltaTime;
if (battleTimer > waitTime)
{
if (Collider2D col && longGrassLayer == "LongGrass")
{
Debug.Log("Collider2D Triggered");
if (Random.Range(1, 101) <= 10)
{
Debug.Log("Encountered a wild pokemon");
battleTimer = 0;
}
}
}
}
why would "Collider2D col" ever be true..?
When it's triggered is what my thinking was going into it
you're defining a new collider and checking if it's not null
it will always be null
unless I'm misunderstanding something
π€ what do you mean call the Collider2D? You handle collisions the same way as always, either some physics like overlap/cast function or some collider and using the collision or trigger messages
checkforencounters isn't the oncollisionenter method
I guess my question is how do I handle collision from the Player object, I know there's an OnTriggerEnter2D function but it needs to be called from the Grass itself
ontriggerenter2D should be called on both objects in the collision
so long as one has a trigger collider
you're not using it though
you're using your own method
The problem with using OnTriggerEnter2D is that it's going to call this no matter what
I need the conditional for it to be LongGrass
you can put a condition inside the ontriggerenter
Something like OnTriggerEnter2D(LongGrass)?
no call it regularly and then put a condition inside the method
use the Collider2D class (https://docs.unity3d.com/ScriptReference/Collider2D.html) to find what properties you can reference
https://youtu.be/QbwgQSwMSGM?t=310
i am making a game similar to this, but having same issue(when the fruit collide its making infinite loop and crashes the unity),
how can i fix that?
Head to https://brilliant.org/CodeBullet/ to start your free 30-day trial, and the first 200 people get 20% off an annual premium subscription.
Twitter: https://twitter.com/code_bullet
Patreon: https://www.patreon.com/CodeBullet
Discord: https://discord.gg/UZDMYx5
Art created by @Dachi.art https://www.instagram.com/dachi.art
can you show your code
how do i paste 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.
both objects register an "OnCollision2D" so you're summoning 2 objects which will collide and repeat this in a loop as far as I can tell
you need to summon one object total
ok
you could do this by comparing age or Y-level or using some central script that takes the average of their positions
how can I do that?
which one
i don't understand "age of y level" and how do i implement the average distance in the code
if you store the age of the two objects you can summon a new object at the oldest one's location so there's only one spawning (likely the one at the bottom)
or you could skip the age entirely and summon an object at the lowest collided object's position which will put it at the lowest point
average distance is just one position minus both positions' distance / 2
ok
that "average distance" is wrong, to get the average point you sum up everything then divide by the number of elements. In this case looks like 2 is always the guaranteed number
so (a + b) / 2
I wasn't giving a generalized average distance formula
there are 2 objects here
the formula you wrote is wrong, thats all.
"one position minus both positions' distance" doesnt even make sense, its just (a + b)/2
can i use the invoke method to invoke the collision after few delay after the first collision?
to find the average distance you just divide the distance by the number of elements, sure, you're correct
to implement the position they'd be at you could honestly just lerp though
yeah mb I worded that weirdly idk
you'd still have 2 objects summoned if I'm understanding that right
also you can't tell which is the first or second collision
they all look the same
not 2 but many objects in single collision
can you elaborate?
what my original code does is when 2 similar balls/fruit collide it makes many balls, and when i attach script to every ball it creates infinite loop
wait... what is Ballstart and Ballend?
theres no need for this, and no. you dont control when the collision events are sent. You may receive a collision event and then do logic after a delay with a coroutine (or invoke but really its worse).
I feel your setup is probably logically flawed though because from the code, im not entirely sure why you're trying to destroy Ballstart instead of teh current game object. I would have a single prefab stored on the script, which is the next fruit that should be spawning. A simple solution to your problem could just be storing a bool on the script like "isBeingDestroyed" and then set both to true on the first collision. Return early if isBeingDestroyed.
Then do the rest of your spawning/destroying logic
it's like ballstart is ball 1 which is colliding and the ball end is ball 2 which is bigger ball that has to be instantiated after collision
such an odd way to go about it
if ballstart isnt the current game object, then thats an issue
yes I tried adding a bool and invoke and invoke didn't work, now how can I use the bool to solve the logic?
learning it the hard way, i know how to do stuff but cant do anything efficiantly
this just doesn't seem to solve the problem at hand at all is the issue
So I am trying to workout what would be a better way to do battle encounters than the system I have currently since it only collides once (not while walking as intended) and appears to not ever actually enter battle sequence... any suggestions?
private void OnTriggerEnter2D(Collider2D collision)
{
// Check for Long grass tag to begin the battle encounter
if (collision.CompareTag("LongGrass"))
{
// Set timer
battleTimer += Time.deltaTime;
// Check for timer for timing of encounters
if (battleTimer > waitTime)
{
// If number occurs, then battle occurs
if (Random.Range(1, 101) <= 10)
{
battleTimer = 0;
Debug.Log("Entered Battle Sequence");
}
}
}
}
well without seeing what you did, i cant really say. Just adding a bool wont do anything by itself. And invoke here also wasnt a problem solver, it does nothing for your issue at hand. Its simply just a way to call a method, with an option to delay it
what is the "it" that only collides once?
also onTriggerEnter runs once
The grass
np
yes, I understand that.
this is going to run once every frame btw
not just once
it's almost guaranteed to execute
well OnTriggerStay here might be weird, because in pokemon you have to move around not just stay in the grass. One fix could be giving smaller colliders but more of them. Otherwise you'll want to just do some checks to see if you moved a certain amount
if i have a method that i want the enemy and player both able to use whats the best way to do that
ontriggerstay + isMoving variable might work?
I'm sure there's a better way to do it tho
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab) && !isOpen)
{
Cursor.lockState = CursorLockMode.None;
inventoryScreenUI.SetActive(true);
TopBar.SetActive(true);
isOpen = true;
//Opend ui behaviour should be here
Debug.Log("Sucessfuly opend inventory");
if(Input.GetKeyDown(KeyCode.E)){
Debug.Log("Go To Next Screen");
}
}
else if (Input.GetKeyDown(KeyCode.Tab) && isOpen)
{
Cursor.lockState = CursorLockMode.Locked;
inventoryScreenUI.SetActive(false);
TopBar.SetActive(false);
isOpen = false;
}
}
Hello i just started programing in unity and im having a hard time understanding why this does not print Go To Next Screen it does print sucessfuly opend inventory so my error should be in these lines
if(Input.GetKeyDown(KeyCode.E)){
Debug.Log("Go To Next Screen");
}
make it public
you'd have to press Tab and E on the exact same frame
GetKeyDown checks if it was pressed this frame
ye but i cant cuz the script is in the enmy
Interesting enough it's working just as intended...
what does this change?
so i have to run it outside the scope then check if the inventory is enabled?
im not tryna use gameobject.find
or just use GetKey for one or the other or both
you don't need to
Check it out, runs just as intended perfectly. Even when I sit in the grass the battle encounter doesn't trigger
just get a reference to your script
π€·ββοΈ if you're ok with the player standing still and it working then sure. Depends on what game design you want
or make some central script
Standing still, not triggering
weird
I can take more screenshots if you dont believe me
take a video
theres a lot of enemies spawnong
then make a reference to your enemy when it spawns or, as I said, make some central script they can both access
i dont need screenshots, add debugs and see for yourself when code runs. Print out from OnTriggerStay2D
depends on your use case
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab) && !isOpen)
{
Cursor.lockState = CursorLockMode.None;
inventoryScreenUI.SetActive(true);
TopBar.SetActive(true);
isOpen = true;
//Opend ui behaviour should be here
Debug.Log("Poop");
}
else if (Input.GetKeyDown(KeyCode.Tab) && isOpen)
{
Cursor.lockState = CursorLockMode.Locked;
inventoryScreenUI.SetActive(false);
TopBar.SetActive(false);
isOpen = false;
}
if(Input.GetKeyDown(KeyCode.E) && !isOpen){
Debug.Log("Go To Next Screen");
}
}
I just moved the input.getkeycodedown out of the other if statement is this fine or are there any advantges to using GetKey?
GetKey checks if it's down every frame
not sure why you mentioned me on that one, that message was for someone else
what you've done checks if you press Tab or E separately
Yup still not triggering even while standing still
seems to have been a mistake
yeah my fault sorry
add debugs inside OnTriggerStay2D, not just your current logic of when a battle sequence begins
look at every single time the method is called
if they care that is
if it works then it doesn't really matter tbh
it will, because its behaviour different from what they think is happening.
It's not because I'm looking at the debug log, you just refuse to believe it's working
you refuse to add more debugs, and really i havent even seen the updated code but if you simply changed OnTriggerEnter2D to OnTriggerStay2D then this doesnt do what you think it does.
I agree
if(Input.GetKeyDown(KeyCode.E) && !isOpen){
//Logic For Screens
if(inventoryScreenUI.activeSelf == true){
Debug.Log("Inventory Was Open");
}
else{
Debug.Log("Inventory Was Not Open");
}
}
How can i check if a ui element is active i tried searching online but this does not print anything?, No Console errors either
what is your ui element?
I can open source the project if you want to debug it yourself π
its a panel
π€·ββοΈ you seem to misunderstand how much I care. I'm simply pointing out an issue. This isnt my game that'll suddenly reach "why isnt this working, it was working before"
can you show it in your inspector
that's just a gameobject
your .activeSelf should work fine
so long as you're enabling and disabling the gameobject
ah i see my mistake i used !IsOpen instead of IsOpen in my if statement
another quick question since i switched from lua to c for my projects
lets say i have a topbar and i have refrenced it in my gui script
Do i have to create a public varible to edit the content label or could i do something like in lua
topbar.Contentlabel.text = "string"
or do i have to create a refrence for each thing im edeting
so long as you have some reference to modify (and so long as your var isn't read only) you'll be fine
in response to your deleted message
i am saying that this behaviour is unexpected, and you dont know what its really doing. You may run into a case where suddenly your logic doesnt work but youve changed no code. Which leads many beginners to the common "it was working before i changed nothing!!". It was flawed from the start, thats why.
Try this, put a wall near the grass and keep walking into it, as in your location isnt changing. I suspect itll enter the battle sequence. Now honestly i dont remember if you could do that in pokemon, but i dont recall it being a thing.
Another thing, how do you plan to customize the walk distance needed to get a new roll at entering a battle sequence? You cant, because you didnt even define this behaviour to happen in the first place.
how would i refrence it tho topbar.contentlabel?
get some reference to topbar first then get its 3rd child (transform.getchild iirc) and you'll have contentlabel
Fair enough, give me a second
TopBar.GetChild(3);
Assets\Scripts\Gui\InventorySystem.cs(83,24): error CS1061: 'GameObject' does not contain a definition for 'GetChild' and no accessible extension method 'GetChild' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
it would be 2
0 is the first child
not 1
oh wait
not GameObject.GetChild
Transform.GetChild
Okay so you're right about the battle sequence triggering when the player runs into the wall, just to check I loaded up the original and it in fact, does not trigger when colliding/walking.
alright thanks
np
What's your proposed solution?
this is something you could honestly keep if you're not trying to make a 1-1 clone. But besides that, this whole thing is because your rigidbody is sleeping. Its not calling OnTriggerStay2D while sleeping, but while moving against a wall its awake.
You could look more into what pokemon actually does, but its likely very different and would require change to your movement system. You could simply check if the player has moved by a certain amount before doing a new reroll, store the last position when you roll for an encounter.
Might be missing something, but why the heck use on trigger stay. In Pokemon almost every event was triggered when the player moved between tiles. Why not do the same in your game?
good point
depends if they're using tiles
I'm using tiles
It doesn't matter if you're using tiles or not
The movement is discreet
You move between 2 points always.
private GameObject contentLabel;
contentLabel = TopBar.transform.GetChild(2);
contentLabel.SetActive(false);
Assets\Scripts\Gui\InventorySystem.cs(84,32): error CS0029: Cannot implicitly convert type 'UnityEngine.Transform' to 'UnityEngine.GameObject'
When you reach the destination point is when events should be triggered
Okay sorry give me a second there are two solutions being proposed here I need to decipher the proposals
getchild returns a transform
you need to do GetChild(2).gameObject;
I think their movement is with rigidbody, so what i said above about looking into what pokemon does would likely require changes to movement
if its not a 1-1 clone then honestly OnTriggerStay is fine there
I want to be as faithful to the original as humanly possible so I'm open to suggestions on how to improve it
I guess it depends on how they implement it. Even with rbs it's possible they have a discreet sort of movement, otherwise it wouldn't behave like the one in Pokemon.
Share your character movement implementation
Here's the PlayerController script. It's not much but it's honest work https://gdl.space/ixuvirekok.cs
and how can i change the text im using textmeshpro
Ok, so I guess bawsi is correct.
I guess you can stand in between 2 tiles, right?
i tried using .text
@teal viper yeah I'm not using a grid based movement system yet
That's beyond my current comprehension
tons of info online
Well, if you're planning on doing it, you should do it now, because everything else would depend on it.
https://stackoverflow.com/questions/67411554/how-to-change-text-by-script-in-unity
I tried searching online before asking but i think my seach query was not good enough i apologize
@severe shard
this should help
Yes i will read it thanks
i dont mean to deter you also, but consider kinda going in your own direction. Id say grid based movement could be worth implementing, if thats what pokemon does. You dont really need to clone pokemon though, like this clearly isnt gonna be something you sell as your own original idea. Theres not really a reason to spend tons of time rewriting massive parts of your code, when you could make something that works and move onto new things.
I think the movement feels close enough that it wouldn't be harshly judged if it didn't move in a perfect square everytime they moved
But then again if I want it to feel like the original it's a point of contention...
Very grateful for the feedback and insights. I need to revisit the drawing board
https://paste.ofcode.org/38CTnKBAMLbLSrM3EeL2LZ5
I solved the issue and this is the final code
@spare mountain @eternal needle thanks for the help
π this is gonna go wrong fast
i think so
you dont want a static bool, because this means the bool is associated with the type Ball_mechanism. So this means every single item isDone or isnt done at the same time. You want this bool associated with the instance of the ball. Meaning one ball should specifically store if its done (meaning being combined i guess?). After you do this, that invoke also isnt needed
oh i did that my mistake
theres definitely more issues here, like line 33 you REALLY shouldnt use the find functions here. You already know which object to destroy, its passed to you with (Collision2D collision) and then you destroy the current game object too.
After you make isDone to not be static, meaning every ball has its own isDone value, you now also want to set it to true on the other object you are about to destroy.
wait, when I removed static it started to break again, I guess in every collision of any ball it reset the bool and stops further collision, is that right?
what shall I destroy? i don't know the efficient way of destroying the game object that collides with the same type. what could I do here
the bool is being used as a way to know if its already been combined into another ball. This is the order that the logic should happen
The balls collide, collision event sent to one ball:
That ball checks if its already been combined into a new ball, check if the other ball has been combined. If both arent combined, combine them, and set the bool to true for both objects. Destroy both objects, spawn new ball.
Collision event sent to 2nd ball:
The ball checks if its already combined, it sees that it has been. Do nothing
how do i know what collision ball is going to collide, like what method i could use
im not sure what you mean by that, you dont need to know which is going to collide. You just need to make sure only one does the logic
maybe look into more c# basics, because im not sure if you know really how to set a bool on another object
ok i will try
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.VR;
public class ColorAddUp : MonoBehaviour
{
public ColorPureBlue ColorPureBlue;
public ColorPureGreen ColorPureGreen;
public ColorPureRed ColorPureRed;
float RedAddUp;
float BlueAddUp;
float GreenAddUp;
void Update()
{
RedAddUp = ColorPureRed.PureRedValue;
BlueAddUp = ColorPureBlue.PureBlueValue;
GreenAddUp = ColorPureGreen.PureGreenValue;
Color myColour = new Color(RedAddUp, BlueAddUp, GreenAddUp);
PhotonVRManager.SetColour(myColour);
}
}
PureRedValue is a string
RedAddUp is a float
strings are not floats
then you can't make a new Color with it
Color doesn't take in 3 strings
this is surely some AI suggested code.. why do you need a ColorPureBlue along with other colors? Literally just define it using a number
I need a whole script for every variable!!! >:((( π€
/j
NO
I wrote it
caps lock
lmao
dear lord, do some basic c# first and save yourself the headache
π
you changed "them all" to floats... where?
π
you're going to have so much more trouble if you don't learn C# first
#π»βcode-beginner message
just did. go learn some basics because you arent gonna struggle your way through making a VR game. Also configure your !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
reeeeeeeeeally stupid
just tell me what to do first
best way to not get help is to demand help
please tell me what to do
ColorPurpleBlue isn't a variable you've just used two types on one variable
it'd be like saying "float string e"
NO
'public' is not a type
its not supposed to be a variable
BlueAddUp Is a variable
Im trying to get that variable to equal a value in a script
you're trying to convert apples to oranges
ColorPureRed.PureRedValue should be a float
configure your IDE #π»βcode-beginner message
they've got a lot more issues than just their IDE π
huh
sorry typo
it's a string
it needs to be a float
even more than it was 2 seconds ago
go configure your IDE though
ok
you can deal with those if you want π im simply pointing out the IDE and not helping further. Theres a clear lack of fundamentals so you'll just end up writing the code for them
agreed lol
wait
delete them?
can you show line numbers please
did you save your file
yes
okay go configure your IDE and you'll see where the issue is
configuring your IDE will help a ton
I cant microsoft visual studio is saying I dont have wifi fsr
I'm going to bed
@drowsy oriole This server requires you to have a properly configured !ide in order to be helped. Until that time stop spamming the server and please look into getting that working.
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
Especially in your case the issue can be omitted by having your editor set up correctly.
And please don't spam random users. Helper is a user, not a role you can ping
Because there is no need to. The whole point of these channels is helping
Vector2: How to get green when i have red, white, and blue? The length of yellow line varies as well
yellow line is perpendicular to the long line
You cant get the yellow line from a straight line with three points. You either have to know the distance of yellow or the angle from blue or red towards green.
length of yellow line is a variable, controllable
thats another infromation than "varies" π
Look up how to calculate a line perpendicular to another line and passing through a point (the point being white)
Hopefully that is even perpendicular in the first place, otherwise this question doesnt make sense
Is it bad to make functions like these and Update() for example async? I wonder what consequences that has, especially for Update?
public async void OnDrop(PointerEventData eventData)
Not sure what you mean. Call an async function from update?
Update wont wait for it to finish, so you just start that function on every frame. Whatever the function itself does might overlap with a more recent run of its code then
async void Update() like that, because I need to await functions inside of it sometimes, which is probably bad design
You just cant async Update
not actually sure if I do it in any of my Update fuctions, but the OnDrop is another weird example
doesn't give any errors
Taking of car wheels does not scream at you it cant drive. It wont just work
ok good to know
kinda expecte that yeah
so I guess it's the same for stuff like OnDrop?
well maybe not π€
Depends on where it gets called. If its a single call method, it might be also working as async.
{
// Equip the dropped item
public async void OnDrop(PointerEventData eventData)
{
// eventData.pointerDrag is the gameobject being dropped
if (eventData.pointerDrag == null)
{
return;
}
// Get our item
Item droppedItem = eventData.pointerDrag.GetComponent<Item>();
if (droppedItem == null)
{
Debug.Log("No dropped item.");
return;
}
droppedItem.dragged = false;
await droppedItem.EquipItem();
}
}```
Why exactly are you awaiting at all when the equipitem is not yielding anything afterwards ?
What Unity Version are you using btw
I just cant find the OnDrop method in the docs for that version
latest version supported 2019.1 ? Hm, im confused
What is OnDrop actually doing?
That's because Unity moved that doc
To an oblivion
You got the updated one? cause I cant find it π
π you were faster
it detects where you let go of the cursor when dragging
Okay, so its a onetime call, id say,just try to await something simple and after a second, call a dbeug log and see if it works then.
you can always call another async function from the not async OnDrop too
it just feels safer this way, but yeah could test if it actually works
it needs to work in EquipItem though
so I'm afraid if I don't use await to call EquipItem, that won't await stuff either
Await is literally awaiting the other function to finish. So its just preventing your OnDrop to continue while Equipitem is not finished. If you dont await it, it will just call that function which will do whatever its supposed to do and ondrop will finish on its own
Its right there what will happen. Its not an error, just a hint for you that it will continue the CURRENT method (OnDrop) without waiting. If you do not need to wait, ignore it
the green underline kinda triggers me lol
I can tell π Then just make your ondrop async and see if it works.
So the unity core will have its wiggle line somewhere but wont show it to you π
Double trigger! π
but not sure what the effect is
Try OnDrop async