#๐ปโcode-beginner
1 messages ยท Page 103 of 1
idk how to explain it but im trying to make an animation for a button where when you hover over it theres a bar that extends just above the word that goes to the right then one that goes down the right side then one across the bottom to the left and one up the right side and i have a ui element thats a bar and it at the top and if i increase the RectTransform.right value the bar will extend along the top but idk how to go abt changing it in code
do you know how id go about doing that
if you're dealing with UI just use the anchoredPosition
But the 2 codes which I send are ok?
Or need a cache too?
thats the one I meant, the Animator line
looks fine otherwise, although I would approach it completely different
my toilet would probably have enum states
what does OnGUI do?
or
when is it called
ehh they're just drawing some sliders in the example
its a quick way to draw UI elements on screen without canvas
for testing mainly
how would i use anchoredPosition to change the scale of the object
like i want to extend it to the right
you don't you use sizeDelta
but if i change the scale it extends to the left aswell
because the pivot/anchor is in the center
move the pivot to the left side
to do this do i change the pivot to X = -1 and Y = 1?
when i change this value to 1 it just makes the recttransform values this
is there i way i can make the right value just go from 350 (which is not extended) to 0 (which is extended)
You need to change the anchors
to what
ive changed the anchors to match the corners of the top bar and now when i hover over it the values change to this
yellow
but i want the top bottom and right to be 0
yup
Huh why is it set to stretch
idk it was automatically was set to that
That's how you set the anchors
Ok I saw this comment a little late and I appreciate the suggestion but what I implemented was that it would basically play even when the seen reset so the same thing as before but this time it mutes/freezes the audio when transitioning to a different scene for example if I am playing and go to the main menu the audio from lvl 1 pauses then when I go back to lvl 1 it resumes same place you left off it that makes sense
Do you think this is a good work around or do you see any bugs around the corner I should be aware of?
https://gdl.space/yorabuyaka.cs I want to adapt this script to top down 3D movement
how do I do this?
Use a non-2D Rigidbody
Hi, I am trying to make my player move in the direction they attack, and I was wondering why this might not be working. There is no movement when I attack.
https://gdl.space/yaxobebiva.cpp
Does anyone know why this is not loading the "DesiredScene" after the 5 seconds? ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CrossSceneElevator : MonoBehaviour
{
GameObject PlayerController;
GameObject PlayerCamera;
public string DesiredScene;
AsyncOperation Progress;
private void Start()
{
PlayerController = GameObject.FindGameObjectWithTag("Player");
PlayerCamera = GameObject.FindGameObjectWithTag("MainCamera");
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
StartCoroutine(Wait());
Progress = SceneManager.LoadSceneAsync(DesiredScene);
Progress.allowSceneActivation = false;
GetComponent<BoxCollider>().enabled = false;
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(5);
PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);
PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);
PlayerPrefs.SetInt("Elevator", 1);
SceneManager.UnloadScene("1.12 Hall");
Progress.allowSceneActivation = true;
}
}```
You start the async load of the scene immediately. It probably takes less than 5 seconds to load
Which is what i want. The setup of my scene, is having the player enter a elevator, which loads the next scene in the background, and waits about 5 seconds, then loads the next scene.
And what is currently happening
It loads the scene in the background, but doesn't switch to that scene after the 5 seconds.
What happens if you put the allowSceneActivation before the unloadScene
Same thing
I'd suggest adding some logs or stepping with the debugger
Let's try commenting out the unload scene completely
It's probably unloading this object, thereby cancelling the coroutine, before it finishes loading
I would, but i'm not sure where, it doesn't call the "Wait()" function at all.
Ok
Oh, that's a completely different issue
I had assumed you made sure the function was even running first
Well actually i'm not sure, thats more of a assumption, i'll check.
Never assume
Okay, so it is calling the coroutine, so it must be having issues with the "Wait for seconds" line, or Stopping somewhere.
Put a log after the wait
Hmm, thats interesting, there is a log, meaning that the coroutine is working, just not loading the scene.
So continue with the previous plan of commenting out the unload
Did that, and it changed nothing.
Oh, here's a thought, if you collide again while the operation is going, you get a new async operation and never re-enable allowSceneActivation on the original one
You should only run that code if progress is null
I disabled the collider though.
Let's make sure. Log after you set progress and see how many times that log happens
why not while loop yield return null while the task isnt done and move all your code into the coroutine
IEnumerator Wait()
{
var progress = SceneManager.LoadSceneAsync(DesiredScene, LoadSceneMode.Additive);
//other stuff
while (!progress.isDone)
{
yield return null;
}
//other stuff
SceneManager.UnloadScene("1.12 Hall");
}
something like that
Okay i'll do that now, and i also noticed that the courotine goes through every line of code and stops right before the allowsceneactivation = true.
Okay so now i see that it also goes through the allowsceneactivation line, so i'm not sure why it isnt loading the scene.
Does it work if you load it synchronously?
Yes
Okay, then share your current code
With the Scenemanager.Loadscene?
You can comment that part and keep it for reference. I'm more interested in the latest async loading code
Here: ```public class CrossSceneElevator : MonoBehaviour
{
GameObject PlayerController;
GameObject PlayerCamera;
public string DesiredScene;
AsyncOperation Progress;
private void Start()
{
PlayerController = GameObject.FindGameObjectWithTag("Player");
PlayerCamera = GameObject.FindGameObjectWithTag("MainCamera");
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
//SceneManager.LoadScene(DesiredScene);
StartCoroutine(Wait());
Progress = SceneManager.LoadSceneAsync(DesiredScene);
Progress.allowSceneActivation = false;
Debug.Log("Done");
GetComponent<BoxCollider>().enabled = false;
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(5);
PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);
PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);
PlayerPrefs.SetInt("Elevator", 1);
SceneManager.UnloadSceneAsync("1.12 Hall");
Progress.allowSceneActivation = true;
Debug.Log("Done again");
}
}```
Btw, what makes you think you need to call UnloadSceneAsync?
Can you comment that out and see what happens?
I dont want that scene to still be loaded in the background once i load into the next scene.
LoadSceneAsync unloads any other scene before loading the new one.
Unless you load it additively
Also, everyone assumed that you don't have any errors in the console, but is that true?
Yes that is true.
Okay. The only other thing that bothers me is that you're waiting for 5 sec. What if your scene is not loaded by that time? I think you should use a loop and check the progress too.
Kind of like they do in the documentation example:
https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html
Like this? IEnumerator Wait() { while(!Progress.isDone) { yield return null; } PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x); PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y); PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z); PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y); PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x); PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y); PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z); PlayerPrefs.SetInt("Elevator", 1); //SceneManager.UnloadSceneAsync("1.12 Hall"); Progress.allowSceneActivation = true; Debug.Log("Done again"); }
Not if you set allowSceneActivation to false
When allowSceneActivation is set to false, Unity stops progress at 0.9, and maintains.isDone at false. When AsyncOperation.allowSceneActivation is set to true, isDone can complete. While isDone is false, the AsyncOperation queue is stalled. For example, if a LoadSceneAsync.allowSceneActivation is set to false, and another AsyncOperation (e.g. SceneManager.UnloadSceneAsync ) initializes, Unity does not call the second operation until the first AsyncOperation.allowSceneActivation is set to true.
Please read the docs
And look at their example.
This would get stuck in "infinite loop" if you do set it to false before.
I need help, I am using this script for when my enemy dies. Is kinematic gets switched off but animator isnt getting diables
Can you show the inspector for the object with Ragdoll?
I might have done what you were mentioning ``` IEnumerator Wait()
{
yield return null;
Progress = SceneManager.LoadSceneAsync(DesiredScene);
Progress.allowSceneActivation = false;
while (!Progress.isDone)
{
PlayerPrefs.SetFloat("POSX", PlayerController.transform.position.x);
PlayerPrefs.SetFloat("POSY", PlayerController.transform.position.y);
PlayerPrefs.SetFloat("POSZ", PlayerController.transform.position.z);
PlayerPrefs.SetFloat("ROTY", PlayerController.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTX", PlayerCamera.transform.rotation.x);
PlayerPrefs.SetFloat("CameraROTY", PlayerCamera.transform.rotation.y);
PlayerPrefs.SetFloat("CameraROTZ", PlayerCamera.transform.rotation.z);
PlayerPrefs.SetInt("Elevator", 1);
//SceneManager.UnloadSceneAsync("1.12 Hall");
Progress.allowSceneActivation = true;
}
}```
Everything is frozen
Again, check the docs page that I linked. The part where they check the progress is crucial.
How do i unfreeze my unity editor?
Oh ok nice!
Is it because of an infinite loop?
Could try breaking with the debugger in the loop and manually changing Progress.isDone if it allows you.@twin bolt
I need help on one more thing
You still have while (!Progress.isDone) after setting allowSceneActivation to false
Oh, I see how you have it. Interesting
I think
This is a code that detects when the enemy is hit and takes damage. on some occasions the weapons fires faster and some of the bullets are ignores like a delay between each registered bullet. How can I fix this so every bullet is registered
If it's in play mode and you're certain where it's freezing, you could try attaching the ide to the running process with a break point at the looping location in code.
Is TakeDamage a coroutine? It seems like you disallow damage for some amount of time
And how are the bullets moved?
Ok, where are isHit and routineStarted set true?
Also, how are the bullets moved? With the transform or a rigidbody
IsHit and routineStarted are set true for the projectile scripts and they are moved using transform
Well, transform movement will usually cause issues.
It is just teleporting from one point to the next. It can teleport directly over something easily
If you want to use the transform, raycast ahead of it to check the space in between the teleportation points
Or just use a rigidbody and set interpolation on and collision detection to continuous
I think the delay between the registered hits is caused by the routineStarted bool, that's why I was asking about it
Should the bool be removed entirely
because I was reusing another script but I think this one doesnt need the routine started bool
Well, I still have no idea what routineStarted represents, so I have no idea.
Are you starting a coroutine that causes bullets to not cause damage for some amount of time, because that's all I could guess
I think I understand what is happening here and ill figure the rest of it out
Thanks for the help
nota code question
#archived-lighting
I just realised something, none of my asyc scenes are loading, is there a limit on how many scenes you can have in the background?
If you aren't loading additively I think it is limited to 1
Same as normally loaded scenes
can someone send me a code of mobile player controller mobile (like player movement joystick and rotation)
I really doubt anyone will, we can help you if you have an issue though
okay
Okay i may have found the issue, i think one of my other scenes loaded in the background is what is breaking it, its waiting for that scene to be loaded.
Is there a way to make a float Round itself to 1 or -1 from a float if its above 0 using one of the mathf functions?
I would think calling LoadSceneAsync would cancel any other scene being loaded and load the new one, but I really don't know. I've never tried doing more than one when not doing it additively
If it's above 0 how would it round to -1
sorry what i meant was turn into a whole number
Does Loadsceneadditive, work similar to Async. Does it remove the wait times?
I think this is it, im just tracking the mouse X to either be 1 -1 or 0
No, there is no such thing as LoadSceneAdditive
It's just LoadScene and LoadSceneAsync with the second parameter set to LoadSceneMode.Additive
It means is a yes?
Well
I need this script because I need to test something
What do you suggest i do, to remove those wait times between loading scenes normally?
It means an absolute no. If you want to gamble on the extremely unlikely case someone will just give you code, you can.
Or you can show what you have done and explain why it didn't work, and we can help you with ig
You always have to wait somewhere. That is unavoidable. Async just makes the wait happen while the player is still playing
Oh well I did this
Joystick works but I need to add the player movement and rotation
This video was made before UI added
Have a small "loading screen" loaded as DDOL or something and enable it/transition to it between actual scenes.
hey so im coding a wall running script, but if i look slightly towards the wall instead of straight forward i slow down. does anyone know of a way so i can make it that you can look within a few degrees and the player wont slow down?
when i flip the character it flips to far because of the sprites
is there any way to fix this?
not a code question.
try putting pivot at the same spot by the feet
sorry but would that work if I rotate the gameobject because i need that so that its weapon has a hitbox
flip the gameobject by rotating its x by 180
you rotate on y 180 to flip in 2d
how do I make this a System.Func<bool>
but i need the hitbox to flip with it to so that it will be on the side its facing
there might be something at the top saying using Systems.Numerics maybe
it expects a func<bool>
youpassed a bool
how would I change a bool into a func<bool>
you could prob make it anonym func. WaitUntil(()=> Condition == something)
=> worked, thanks ๐
so what?
im thinking of create a arbitrary time counter by using time.delta time to increase a float variable and use that variable to do other time based task
are\ there any better method?
if its global make sure it updates before everything else
Isnt this Time.time with extra steps?
thought it only count up and cant be reset
It cant but why do you need it to reset? Usually you just calc a div in time so you if(currentTime-prevTime > someNum) doThing() prevTime = currentTime
Oh neat
Wait it's it gonna have problem like everything is sync together? I want a game object to have it own counter when created
If you keep track of prevTime in each gameObject then I dont see how itโs gonna be synced
class MyScript{
float startTime;
void Start() {
startTime = Time.time;
}
void Update()
{
print($"Internal time {Time.time - startTime}");
}
}
What exactly are you trying to do I might have a git repo for you
Hmmm I see. I just assume how it work while going to school. Will figure it out for my own
public class Attacking : MonoBehaviour
{
public int attackDamage;
public float attackDistance;
public float attackDelay = 0.4f;
public float attackSpeed = 1f;
public type state;
public enum type
{
fists,
weapon
}
private void Start()
{
state = type.fists;
}
private void Update()
{
Weapon();
}
private void Weapon()
{
if (state == type.fists)
{
attackDamage = 1;
attackDistance = 2;
attackSpeed = 1f;
attackDelay = 0.4f;
}
if (state == type.weapon)
{
attackDamage = 2;
attackDistance = 3;
attackSpeed = 1.5f;
attackDelay = 0.4f;
}
}
}
Instead of the attack damage or any of them being set to 1 and only being able to be changed in the code how would I change it in the inspector
you should already be able to change these in the inspector, but your Weapon() logic is running every single frame, so it is resetting them back to these values in code.
you dont need to run it every frame, only when the state is updated
so how would i fix it
dont have a public field for the state, use a property or method so you can run logic everytime its updated from an external script
You can move the point of origin position of each sprite in the sprite editor.
im using instantiate to spawn my bullet
why when it spawns in the hiearchy it is set to inactive please help. Also it was working like 5 seconds ago.
you really dont need to crosspost this to 3 channels, look at #854851968446365696 on how to ask properly
do you know how to fix it?
My game screen is made with UGUI, and I'm using Post Processing's Bloom effect, and I realized that it will work on all the Images in my screen, and I only want one of them to glow, and the others don't, how can I do it?
yes, you fix it by first asking the question properly. look at the #854851968446365696 on how to ask and someone will help
this is a coding channel, you probably want like #๐ฅโpost-processing
so you dont know?
sorry for crossposting just please help me
thanks
Is this too much?
Dictionary<int, List<Dictionary<string, object>>> returnDic = new Dictionary<int, List<Dictionary<string, object>>>();
The outer Dictionary would hold monster id's
The list is then a list of the combat logs each with it's own inner dictionary of log values
Or is that perfectly standard in C#?
Is there a reason you're using a dictionary instead of a list for the outer collection?
why the value cant be a custom class ie Dictionary<int,List<LogClass>>
dictioanary<string,object> sounds like json format
im using instantiate to spawn my bullet
why when it spawns in the hiearchy it is set to inactive please help. It was working and i dont know what i did
Is the prefab active?
since the object is inactive
yes
because it has the monster id as key
check if something that set it to be inactive, especially the code after Instantiate
i have a question if i make a game with unity and share it with friends and play it multiplayer will it cost anything
Is the parent active?
yeah
i even tried setting the prefab to active when it is instantated but that still didnt work
Are there any components on it that's setting it inactive?
Is the spawner/manager setting it inactive?
most of unity gaming services has a very generous free tier, check the website for their pricings
no i didnt add or remove any compopnents it just randomly stopped working
i did but i dont understand anything about the fee thing
Surely one of the above suggestions isn't what you think it is.
which one do you want to use? what part do you not understand?
the personal program, i dont understand what is it and how much is it
well you did something somewhere that caused it to stop working
might be something you think is completely unrelated, but things don't randomly stop working ๐
personal program of what?
i added code to make it different but it stopped working when i did that. so it was probably that but then i ctrl + z all the way back to the start and it isnt working
what can make it set to inactive
did you ctrl z a reference that you need to set in the editor?
unity personal, free version of unity
no i checked the player prefab and everything is set to the right thing. like when i click it works perfectly but the bullet is just set to inactive
if you are using unity as a single person / hobbyist it's free to use
also completely not related to coding
so i can share the game for free also?
why don't you just read the website instead of coming to a chat that has nothing to do with your question and expecting others to do your research for you?
it took me 15 seconds to find
ok sorry i tried but i couldnt find it thank tho
im gonna deelte all the shoot code and write it again
show the line of code that instantiates the bullet
also if you open your prefab (double click it so it's open in your scene)
then in the inspector on the right, is it active?
if (Input.GetMouseButton(0) && canShoot)
{
Instantiate(bulletPrefab, firePoint.transform.position, firePointOrientation.transform.rotation);
StartCoroutine(ShootCooldown());
}
yes it is set to active
yeah its on
show a screenshot of your full unity screen with the prefab open
there are ways to do it yea, but you really wont have fun doing multiplayer if you know nothing about unity. multiplayer is never easy
it's getting easier & easier with the tools unity offers
After a month of using c#, I can finally fix compiler errors sort of easily
any SetActive in that script?
no
are bullet1 & 2 active?
yeah
what if you drag the prefab in your scene? is it active?
yeah
then you have code somewhere setting it to inactive ๐
alright thanks
is that the only way it can be set to inactive? if i have it in code set to inactive?
because im 100% sure i do not have any setactive codes anywhere
ctrl f your project for SetActive(false)
yeah i actually did that
if you're talking about setting up a p2p connection then sure, that is not the hard part. actual networking is still not easy by any means
how. I put gameObject.setactive(true) in void UPDATE in the bullet script and it still is set to inactive
but unity has tools now that do all the networking for you?
is it something in the network component? don't know much about that
yeah, thats what im thinking it basically has to have something to do with the network stuff. If im being honest i also dont know too much about it aswell
try deactivating the network component and see if your bullet works
unity NGO definitely does not do everything for you at all. Setting up a connection is not what i am referring to, i am talking about the actual code
but like bawsi is saying, multiplayer is hard ๐
nothing really works when i disable it
NGO? I've seen some tutorials on Multiplay and it looks like it just does everything for you
but I didn't go very deep
and yeah it will still be much harder than a single player game even with all the tools
it confuses me so much because it was working like 5 seconds ago
well you did something ๐ but I've never worked with network components so can't help with that
but it makes a lot of sense that if you miss-configure the network component the bullet wouldn't appear on the client/server
you'd probably get more help in a fishnet related group (if one exists). You could try spawning a non networked prefab to see if that works, then add the network object and see if it breaks.
Honestly i suspect theres a warning or error, or something. I dont see a console anywhere in your screenshot, so I assume you just arent using it
thats the only errors
while you have an error in your code unity can't re-compile the code
so as long as you don't fix that error, your code won't update
thats only there when i click play because the camera is being set to a parent of the player and it isnt instantly doing it because it only shows up the camera when i click client and server
try a debug.log when you spawn the bullet and then another one for the active state
then keep adding debug.logs until you figure out what's happening
at least that's how I fix my bugs
hoow can i make a debug.log for the active state?
Debug.Log(gameObject.activeSelf)
should it debug the state its in
like if it is active or not
ok so i just found this out. When the game is started and i drag in the bullet prefab it is set to inactive
nvm that is for everything i put in
if i put the bullet prefab in the scene then click play. it automatically sets it to inactive
it's most likely just not set up properly for the network
it might only be displaying on the server or only on the client
or it might not be set up so it defaults to not display
time to go watch some tutorials on networking ๐
i guess thats all i can really do? it doesnt make sense though i didnt do anything to make that happen, or atleast i dont think i did
maybe you removed a piece of code that makes it active in the network
or maybe you clicked something in the network component
or maybe something in your client/server setup changed
or maybe none of that
it's impossible for anyone to tell
if it was working before, just re-do what you did earlier
i did. i ctrl z all the way to the very start of my session
you need version control if you arent using it
this would've been like a 2 second issue. you look at the code in a previous commit, see the changes, done
Not the right channel im sure but i cant find a 2d channel lol
Player goes behind trees in the main menu, yet in the game they're in front? Any idea why this would be? Tried trouble shooting by changing tags around and im stuck, is it a script problem or anything else?
any recommendations for version control with Unity?
I'm currently just pushing all my files to github, but haven't really needed to use it so far
I use github for my projects personally
apparently the unity built in one is quite good too, used collaborate in the past and never had issues
github as you are using, pretty much always. Git is used in every other CS field so its very useful to be able to transfer this knowledge elsewhere.
Just commit every often you make changes, I havent needed to go back to previous commits yet but at least i can if i want to
UI/canvas works completely different from camera
in UI it's the order your objects are in the hierarchy that determines what is in front
not sure what the correct terms are here
is there any other way i can go back to another commit without github or anything?
there is no commit if you arent using version control
also you can put a debug.log in OnDisable for your issue and try to see what the stack trace is. maybe itll tell you whats disabling your object
I've never had issues with it tbh
where is OnDisable?
nvm found it
how can i use that to find out what is doing it
does it save references & stuff on gameobjects? I guess those are just saved in files somewhere as well so why not
From my memory yes
I'm terrified of having something go wrong in my project and having to restore a commit LOL
Its been a while since i worked on a big 3d project lol
The only issue is you cant upload very large files, but those can be shared by any other means.
I think the other solutions are garbage, the skillset arent transferrable to any other fields of work. Their "benefit" is that they are integrated with your IDE, but it is useless. There is premade GUI's like github desktop, where everything is just done in one click
also still need to set up dev environment and database & stuff -_-
meanwhile ppl are playing my game lol
I worked on a spaghetti code game with like hundreds of ui elements and it saved it all fine but that was a few years ago
i doubt it would have changed tho
my collider isnt working idk why can someone help
yes of course it is
do you think you have provided enough information for anyone to help you?
i dont know what is confusing about what i said. You should probably do some intro to c# lessons if this is confusing, especially if you are trying to do networking.
#854851968446365696 you're supposed to actually read the read-me
that is code which just places down something and i can buy it and whatever it just for tower defense
yea what for i read it
anyways it should change to a red colour or be not placeable but it still is placed down
ok then follow what it says..
you have ben very negative all your words to me, not sure why. Also i never said it is confusing
a solution is just helping me
and not judging me presumabally not understanding that
this chat is for people asking questions and if i ask a question and you judge me you are not very good and should just not respond
what is negative in that reply? I am telling you I dont know what is confusing, your question made no sense. If you feel it is negative that i said to do intro lessons, then you are taking the wrong meaning by it.
bawsi has not been negatie at all, in fact they have given good advice
did you bother looking up what a stack trace is or how to debug it?
we're not here to make your game for you, we're here to offer tips and advice, but you still have to do the work yourself
no, i tried asking him but he just said i need to take lessons
You really cannot ask "how can i use that to find out what is doing it" and expect people know what you want
what is "that" and "it"?
you come here to ask things after you've spend an hour trying to figure them out yourself
not because you're too lazy to google something
and me and you have been talking for a while because we cant figure it out
well the reason we can't figure it out is because you're trying to do something that is very hard and seem to lack basic knowledge of both unity and programming
hi chatgpt isnt giving me any answers that work, this is my code for flipping a sprite on its x axis based on rotation but its not working properly, sometimes it flips properly but especially when its moving down to the left it doesnt flip:
public static void Wandering(ref Vector2 targetPoint, Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);
Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;
// Flip the character based on movement direction
if (tempDir.x < 0)
{
// If moving left, flip the character to face left
spriteRenderer.flipX = false;
}
else if (tempDir.x > 0)
{
// If moving right, keep the character facing right
spriteRenderer.flipX = true;
}
if ((Vector2)subject.transform.position == targetPoint)
{
Debug.Log("new point");
targetPoint = RandomPoint(centerPoint, wanderRange);
}
}
so getting a c# basics lesson is solid advice
https://gdl.space/odedamizuz.cpp here is my code currently this just is for a tower defense placement system it took about 45 minutes to get up to this point with a few other features also. It should change colour when it is touching a collider and not be placeable however no matter what it is still placeable and does not change colour and you can see in the console it is logging whether it is placeable every 0.5 seconds, also how much wood and stone you have but just ignore that. Ill show you a video of what happens and it is not what should happen based on the code.
there is that how i should have done it following the readme
any of the people who replied to you (including at the very beginning) could figure it out if this was their project because they would understand the advice we have said to you. You still havent said which part you are confused by, and you also claimed it was not confusing. If it isn't confusing then follow the advice #๐ปโcode-beginner message
If it is, then ask a question
let it go mate, poo is probably frustrated because they can't figure out the issue
they shouldn't take it out on you, but you shouldn't take it personal ๐
this is not nearly enough information to provide help
does it not flip at all when going down left? I would debug what tempDir is, maybe the target point (or subject) isnt where you think it is
noone gonna help me i did what u told me to
apologies let me edit it quickly
i wasnt taking it personally, was just telling them the reality of it. I dont think i said anything negative here
agree, seemed like friendly advice
though telling someone to go follow a course can be a bit triggering ๐
even if you're right
you have a lot of extra semicolons in your code, meaning a lot of these if statements do nothing since the statement part has ended. Is your IDE pointing out errors? I believe this would at least show a warning in mine
if (placeable); being one of those if statements
!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
I updated it to contain the whole function
yea sorry i fixed them ignore them
i understand i probably do need courses but the pasc guy atleast like had a chat and tried to help all of your talk has been 1 sentence saying 1 thing that is helpful then after saying try searching it up instead of giving backstory on it
drop it
it does it just shows where they are on the scroll bar
yeah i dont even know why i said that im bored
did you try to see if it works now? because fixing the semicolons would change a lot here
then i accidentally clicked a keybind which puts semicolons instead of commenting it out
i was just gonna test something
anyone got any ideas whats wrong
if u need more info just ask
https://gdl.space/uhitarezad.cpp here is my code currently this just is for a tower defense placement system it took about 45 minutes to get up to this point with a few other features also. It should change colour when it is touching a collider and not be placeable however no matter what it is still placeable and does not change colour and you can see in the console it is logging whether it is placeable every 0.5 seconds, also how much wood and stone you have but just ignore that. Ill show you a video of what happens and it is not what should happen based on the code.
I think the colors might all just be white now that im looking at this more
the values should be between 0 to 1
make the colors public or [SerializeField] and just see in the inspector what they are
im just making a test where i can manually change between the colors i have selected
give me a sec
ok i commented out the old colour changer and added a function to update which allows me to edit the color in runtime
I recommend handling the mouse input in your update function
this is edited i couldnt be bothered using the website
it is just in a function for readability tho its not really different is it?
ill post vid of what happens with new script
I am not sure I have never touched OnMouseDown event but I recommend using Input.GetMouseDown
i dont really get what this new method is for, where has this color variable come from and where is it being set? Still, you should do what i suggested above and see what the color actually are instead of assuming what the colors are
oh you are doing that in inspector
Wait new SpriteRenderer... is that something you can so in C# above the awake function...?
yea i couldnt get the normal one to do anything for some reason
its just a reference
You should not new Unity objects (except for GameObjects)
the new just means it overriedes the normal ones
im not creating a new one
but you can do that in awake
I know, I was confused about the code snippet he sent...
instead of the current Debug.Log(placeable) i would just debug whats happening in Place(). one of these values probably arent what you expect and you can see which if statements it is entering
There's a difference between redefining variables and creating new instances, they're redeclaring
the issue is that these arent triggering and placeable isnt changing i know the issue i just dont know why
both objects im testing on have box colliders so it should be triggering
There's a resource pinned to this channel for debugging physics messages
no object had a rigidbody im just gonna test now if it works
thanks vertx
oop still not working
yup it still isnt owrking
i found the issue i am using transform.position which bypasses the physics still thanks vertx
ill test tommorow cause i have to go now hopefully i remember.
here is the full code, they definitely move to the correct point they just dont always face the right direction
public static void Wandering(ref Vector2 targetPoint, Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);
Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;
// Flip the character based on movement direction
if (tempDir.x < 0)
{
// If moving left, flip the character to face left
spriteRenderer.flipX = false;
}
else if (tempDir.x > 0)
{
// If moving right, keep the character facing right
spriteRenderer.flipX = true;
}
if ((Vector2)subject.transform.position == targetPoint)
{
Debug.Log("new point");
targetPoint = RandomPoint(centerPoint, wanderRange);
}
}```
how is this function triggered?
its in the Update() of an object but this function is the Az class and is called as Az.Wandering(arguments);
Az is my shortcuts class for custom functions that i will be reusing in this and future projects
so you call this function on every Update()?
it's moving towards targetPosition but rotating towards targetPoint
i do yes
sorry I copy pasted the code of the function
public static void MoveTowardsPoint( GameObject subject, Vector2 targetPosition, float moveSpeed)
{
subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
so that its exposed to you, the targetPosition should be named targetPoint
can you share the exact code you have, without editing it
sure thing:
public static void Wandering(ref Vector2 targetPoint, Vector2 centerPoint, float wanderRange, float speed, ref float direction, GameObject subject, SpriteRenderer spriteRenderer)
{
MoveTowardsPoint(subject, targetPoint, speed);
Vector2 tempDir = targetPoint - (Vector2)subject.transform.position;
direction = Mathf.Atan2(tempDir.y, tempDir.x) * Mathf.Rad2Deg;
// Flip the character based on movement direction
if (tempDir.x < 0)
{
// If moving left, flip the character to face left
spriteRenderer.flipX = false;
}
else if (tempDir.x > 0)
{
// If moving right, keep the character facing right
spriteRenderer.flipX = false;
}
if ((Vector2)subject.transform.position == targetPoint)
{
Debug.Log("new point");
targetPoint = RandomPoint(centerPoint, wanderRange);
}
}
public static void MoveTowardsPoint( GameObject subject, Vector2 targetPosition, float moveSpeed)
{
subject.transform.position = Vector2.MoveTowards(subject.transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
public static Vector2 RandomPoint(Vector2 centerPosition,float range )
{
// Calculate a random direction within the move radius
var randomDirection = Random.insideUnitCircle.normalized * range;
// Calculate the new target position within the move radius around the center
return centerPosition + randomDirection;
}
The only thing that I can see is that the direction should be determined before moving the character but that shouldn't matter until the frame when it reaches the target
it's not really clear to me what you're trying to do
this looks like 2d left & right movement only? but I think you mentioned down/left earlier? so which is it?
add some Debug.Log() in your if statements to see what is happening and let us know what goes wrong
this is the bug
// Flip the character based on movement direction
if (tempDir.x < 0)
{
// If moving left, flip the character to face left
spriteRenderer.flipX = false;
}
else if (tempDir.x > 0)
{
// If moving right, keep the character facing right
spriteRenderer.flipX = false;
}
both branches set flipX to false
yeah thats a typo i already fixed
but it's correct in the earlier snippet so ๐คท
? looks fine to me? what is supposed to happen?
I assume it's the guy on the left who's walking backwards at the start
yup
i mean i only came here because chatgpt cant figure out the issue and i keep looking at the code and being like, i dont see anything wrong
add some debug.logs to see if tempdir is the expected value
ok
not sure if it's relevant
but you have a case for x < 0 and another for x > 0 - can x ever be 0? that is not handled
That's normal. If the character doesn't move horizontally then it doesn't need to flip left or right
was about to say that, thanks
How can i create free space text?
I wanna add a little something here but i can't find out how, tried a google but came up empty for what im aiming fro
If you just need text outside of a Canvas UI, there is 3D text both with legacy and TextMeshPro, under "Game Object > 3D" - if you might need more than just text to appear in the scene and not on the UI, you can change the render mode of a Canvas from "screen space" to one of the other options, depending on what you need: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UICanvas.html
its the spookiest thing it will show in the log that its smaller than 0 but it wont flip even though we can clearly see the code telling it to flip if smaller than 0
Thank you!
Damn it my unity crashed
Guys can someone explain the logic here before i break my pc
The console rounds the values
ohh actually ok thank you
Maybe you should tell us what's wrong
If you're referring to the equality check with the last debug, it's likely due to floating point precision error. Use Unity Math f Approximately
Vectors already use that for comparison
show your current code for the flip again
Should I use Git instead of GitHub desktop for version control?
You might want to look at Extension Methods for this:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
Hey i redid the code where it has its own method that takes transform.position-lastPosition and now it works lo
Lol
Thank u for everyones help ๐ธ
Thats the plan
im trying to make a cemra manager for a turn based game, im trying to make the camera to move a little bit in the direction of the unit that is starting a action, i have a center camera position for the group and the unit position.
i want to move the camera a little bit in the direction of unit but not center on the unit. how can i make a point of position btwn he group camera position and the unit position?
that's what cinemachine is used for. It's a unity package that handles all the camera stuff. I recommend you use that instead of coming up with your own solution.
To answer your question though, you can use lerp:
Vector3 targetPos = Vector3.Lerp(position1, position2, 0.8f);
would give you a point that is 80% towards position2.
yeah im using cinemachine
and thx
๐
may i ask you something guys
does anybody has some idea how to fix this?
the two parameter overload of Instantiate expects an object and a transform to set as the parent. if you want to specify a position then you need to provide a rotation too
im new here so i just wanted to know if its okay to ask questions in this channel-
is it better to write your own script that will aauto adjust a rectransform's width based on a text on its child (checks every Update()) or just keep using layout groups for it?
oh
how
did you click the link i sent?
it's a consistent check so, if I can do it better one way, imma go there
whats up btw
yes
im new at unity, i did a movement but i wonder something, lot of unity tutorial videos has that meshed ground, how can i do that? because its too hard to distinguish around without meshes
then surely you saw the overload that accepts a prefab, Vector3, and Quaternion as well as the example code that uses that overload
this isn't a code question. but it's just a material they are using
i cant find anywere, is there any way to do this?
again, not a code question. and to do that you just use a material with that texture
okay now here goes a code question
hold on-
this happens when i try to change material
it scales the image
still not a code question
how-
if you think it is a code question, then share your code
ur right, where can i ask this thing?
oh thanks
i dont understand you
what part of that are you not understanding?
in the link he provided it gives examples
what is overload
iam not a native speaker of english
a method overload is a method that has the same name but different parameters. notice how in the link i sent there are 5 Instantiate methods immediately visible. those are the overloads for Instantiate
Im trying to stop all spawning coroutines in spawner script, if session ended, someshow even when game does end and bool in script manager set to false, nothing happens in spawn script
private void Update()
{
if(!sessionManager.gameIsOn)
{
StopAllCoroutines();
Debug.Log("All coroutines stopped");
}
}
how do i change the color of an image in code using the leantween library
if session ended
when game does end
this sounds like you're trying to call StopAllCoroutines while in the process of completely exiting out of the game. and that is not necessary, but also Update will of course not happen during that
no, no. I meant when player dies. Nothing to do with exiting application
then you need to provide more context about what is actually happening at the time you expect this code to run. because i don't know if this is attached to an object that is being destroyed, whether it's a completely separate object that persists, etc
void Update()
{
dirX = Input.GetAxis("Horizontal");
dirY = Input.GetAxis("Vertical");
}
}
How can I turn those two variables into a direction vector to apply velocity into the direction the controller stick is facing?
Do you know how to create a Vector2 or Vector3?
sure. There's a spawn object with a spawnScript attached, that is active all the time. SessionManager is also just an empty gameObject with session manager script. When game session starts i set bool value gameIsOn in the sessionManager to true and startInvoleRepeating to spawn spikes from it. In spawnScript in update method as long as gameIsOn == true (read from session manager script), it should allow all InvokeRepeating methods. But when player collides with a spike or an arrow EndSession in sessionManager is called, there i change the gameIsOn to false and it cancels all invoke methods. Ill send all relevant code in a sec
public void StartSession()
{
........
gameIsOn = true;
}
private void Update()
{
if(!sessionManager.gameIsOn)
{
CancelInvoke("SpawnSpikes");
CancelInvoke("SpawnBoost");
Debug.Log("All coroutines stopped");
}
}
yeah, i accidentally copied from other script
public void EndSession()
{
//stop spawner from spawning anything
gameIsOn = false;
enemy.StopShooting();
enemy.enemyAnim.SetBool("EndOfGame", true);
spawner.gameObject.SetActive(false);
loseMenu.SetActive(true);
endScore.text = "Score:" + score;
}
update above is in the spawnScript
please share all of the relevant !code using a bin site. these random disjointed snippets are not providing enough context to know when/where things are actually happening
๐ 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.
Vector2 direction = new Vector2(dirX, dirY);
Hi. I wanted to build my project, but an error pops up (there are 8 errors in total, but they are all related to the class: Editor. To be honest, I took this script from another person from YouTube, and I don't know what this Editor does or how it can be fixed.
Editor scripts should be in a folder called Editor. Then they will be excluded from builds
The ones on the left?
how would I know? look at the scripts and movew the ones using UnityEditor
Do I need to create an "Editor" folder or is it already there somewhere?
Do you see one?
so me need to create it. Thanks
Next time don't just blindly copy code
Anyone able to point me in the right direction for something?
Trying to have multiple doors leading to different rooms and i was wondering how i do it, just pointing me in the right direction would help immensely. I know how to handle scene changes normally (main menu -> scene / Scene 1-> scene2 (If there is only 1 door)) but multiple is stressing me out lol
Yes, I checked everything, and everything worked in Unity itself. I'm trying to do something difficult for myself, but so far it's going through 1 place
does anybondy know why this doesnt work?
what are you expecting that to do and what is it doing instead?
or is this just your attempt at resolving the issue you asked about earlier?
it doesnt do anything
well what're u hoping for?
and it should duplicate particle effect
let me guess, you're destroying this object and expecting that newly instantiated one to persist?
that's why it doesn't work. child objects are destroyed along with their parent objects. and since you are using the overload that specifies a parent you are making the instantiated deathEffect a child of the object you are destroying
just pass a position and rotation instead of a transform
isnt it the same?
no for exactly the reason i just described
In Unity Netcode, I am able to set the NetworkVariable HostID when I am the host. However, it seems that I cannot set the NetworkVariable ClientID when I am the client. Essentially, I want to set a string (ClientID) for the host from the client side. Can someone provide guidance or help me with this?
Hey all, I'm trying to figure out what I'm doing wrong when trying to load a JSON file into a struct.
In JsonLoader.cs:
{
public static TextAsset creatureJsonFile;
[RuntimeInitializeOnLoadMethod]
static void ReadJSONFiles()
{
Debug.Log("Reading JSON Files ...");
try
{
StreamReader sr = new StreamReader("Assets/JSON/creatures.json");
Debug.Log("Read creature file done");
creatureJsonFile = new TextAsset(sr.ReadToEnd());
CreatureDataList creatureList = JsonUtility.FromJson<CreatureDataList>(creatureJsonFile.text);
}
catch (Exception e)
{
Debug.Log("Couldn't read creature file");
Debug.LogError(e);
}
}
}```
`CreatureData.cs`:
```[System.Serializable]
public struct CreatureData
{
public string id;
public string creature_name;
public string primary_type;
public string secondary_type;
public string tertiary_type;
public int max_health;
public int attack;
public int defense;
public int speed;
public string sprite_path;
}
[System.Serializable]
public struct CreatureDataList
{
public CreatureData[] creatures;
}```
`creatures.json`:
```{
"creatures" :
[
{
"id" : "0011"
"creature_name" : "Sheel",
"primary_type" : "Water",
"secondary_type" : "",
"tertiary_type" : "",
"max_health" : 70,
"attack" : 10,
"defense" : 7,
"speed" : 10,
"sprite_path" : "res://Assets/Sprites/Creatures/village/sheel.png"
},
{
"id" : "0021"
"creature_name" : "Flatchling",
"primary_type" : "Fire",
"secondary_type" : "",
"tertiary_type" : "",
"max_health" : 80,
"attack" : 9,
"defense" : 9,
"speed" : 3,
"sprite_path" : "res://Assets/Sprites/Creatures/village/flatchling.png"
},
]
}
What am I doing wrong?
well for starters i hope this is just for editor tooling considering none of those paths will exist in a build
does anyone know what this error means? ```Unable to use UDP port 56638 for VS/Unity messaging. You should check if another process is already bound to this port or if your firewall settings are compatible.
UnityEngine.Debug:LogWarning (object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c:<.cctor>b__6_0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:55)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c__DisplayClass8_0:<RunOnceOnUpdate>b__0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:100)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
you are missing a , at the end of the id lines. btw why not just File.ReadAllText?
Oh my god, can't believe I didn't notice that ๐
I'm still really new to Unity dev. Would File.ReadAllText replace the current use of StreamReader?
yes and the new TextAsset. Read straight into a string varaible
and File.Read is std C# .Net, nothing to do with unity
does anyone know what this error means? ```Unable to use UDP port 56638 for VS/Unity messaging. You should check if another process is already bound to this port or if your firewall settings are compatible.
UnityEngine.Debug:LogWarning (object)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c:<.cctor>b__6_0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:55)
Microsoft.Unity.VisualStudio.Editor.VisualStudioIntegration/<>c__DisplayClass8_0:<RunOnceOnUpdate>b__0 () (at ./Library/PackageCache/com.unity.ide.visualstudio@2.0.18/Editor/VisualStudioIntegration.cs:100)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
what about that do you not understand? The message is self explanatory
how do i fix it
did you read it? It tells you
So something like:
CreatureDataList creatureList = JsonUtility.FromJson<CreatureDataList>(File.ReadAllText("Assets/JSON/creatures.json"));?
Why not just make the field non-static and drag the file there in the editor. No need to read it manually at all. Especially since the way you're doing it now won't work outside the editor
i have no clue how to check my firewall im not gonna lie
yes
time to learn. Start with Windows Defender Firewall
I was trying to avoid using the editor ๐ would this be a problem if people tried to play the game without Unity? (If I sent them a build)
i just got onto my firewall and i have all of the things active
yes, because as i mentioned to you earlier, none of those paths will exist in a build
Oh sorry I hadn't seen this. Is this what Nitku is also talking about?
yes
it doesnt say UPD port 56638 is being used
you'll need to put in a lot more effort than just that
I see, thank you. So I should avoid using paths in code as much as possible?
use Application.streamingAssetsPath and put your file in the Assets/StreamingAssets folder
The Asset directory doesn't exist in the build so don't try to load things from it manually
You can use https://docs.unity3d.com/ScriptReference/Resources.Load.html to load stuff dynamically but why would you in this case
i restarted the editor and now it says a different port
so at some point either VS or Unity or Both asked for network permissions and you said no
is there a way i can say yes, or find why they asked for it
I suppose I could use the editor instead. I was just avoiding that approach so that I wouldn't have to create an AssetLoader object and move it between scenes, but I think I should.
yes, by going into the firewall and seeing which permissions are set/denied
okay
On windows, click the windows key to open the start menu, type in "firewall", open "Firewall & network protection" -> Allow an app through the firewall
when i do that it says the settings are managed by my antivirus so i go on to my anitvirus but when i try to search up firewall on it it brings up an unknown browser then it shuts it down
i somehow fixed it
i dont even know how
Hi all, just me again
Trying to configure the collider on an object to hide another object when initially hit, and to recheck if its already disabled to reenable it, this is my code below. Tried creating a boolean for the object being active but i think i'm approaching it wrong. Any help is appreaciated
Cheers!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorHide : MonoBehaviour
{
public GameObject Door;
private void OnTriggerEnter2D(Collider2D other)
{
Door.SetActive(false);
if(Door.SetActive(false))
{
Door.SetActive(true);
}
}
}
well, does it work?
it doesnt no, it throws me the error of "Cannot convert a void to a bool"
which i amended, yet its thrown me more errors lol
try Door.isActiveSelf
Like this?
public GameObject Door;
private void OnTriggerEnter2D(Collider2D other)
{
Door.isActiveSelf
if (Door.SetActive(false))
{
Door.SetActive(true);
you could also use
Door.SetActive(!Door.activeSelf);
no
Im mostly confused as this is the line that is having isues
if (Door.SetActive(false))
it's actually 'Door.activeSelf'
that gives you a bool that is true if the door is enabled, and false if it is disabled. You need that for your if statement
because SetActive returns void. activeSelf returns bool
show code
public GameObject Door;
private void OnTriggerEnter2D(Collider2D other)
{
if (!Door.activeSelf)
{
Door.SetActive(true);
}
}
how do i access the value of a slider from a child of that same slider
thats much simpler than what i tried to do lol
public class DoorHide : MonoBehaviour
{
public GameObject Door;
public bool isActive;
private void OnTriggerEnter2D(Collider2D other)
{
if (isActive)
Door.SetActive(false);
else _ = (!isActive);
Door.SetActive(true);
}
}
all the errors went away by doing this but uh
yeah, i couldn't wrap my head around the activeself tbh, I'll have to do a bit of research on it
you need some basic c# syntax lessons as well
activeself returns true if its active, and false if its inactive. thats all
also i edited my code i forgot the !
check it out if it works
if u do it without the ! then it sets the door active only if its already active
What do you expect with that else line?
thats very true lol
I've been trying to self teach but I think i may have skipped just a few important bits ๐คฃ
my code caused me to reset to the main menu every some how?
you should use events for some stuff so you dont couple stuff like MainMenu in a small component
interesting, this didn't actually work
of course it didn't, it is incomplete
turns out i just forgot to change the build index lol
should also prob do it like this:
[SerializeField]
private GameObject _door;
instead of public GameObject Door;
how do i set a text object's text to the value of it's slider parent
what does the _ do?
it doesnt work cause you still need a trigger in your scene with this script. and assign the door in the inspector
Nothing. It's part of the name
Just convention
Private instance fields start with an underscore (_).
oh right, today's a learning day. Doing my first proper attempt at a gamejam to try and force myself to learn some of the basics (small scope game)
make a script with a reference to the text and a method with no return value and a float parameter. Add the method as a listener to the event of the slider's OnValueChanged event. Set the text variable of your text reference to the value of the parameter converted to string.
turns out, I had set the player too close to the door in the corridor
thank you ๐
so it was resetting me to the main menu
ALso it prob should be like this:
[SerializeField]
private GameObject _door;
private void OnTriggerEnter2D(Collider2D other) {
_door.SetActive(!_door.activeSelf);
}
i should rework how my triggers work
colliders wont work here lol
A raycast would be overkill wouldnt it?
Raycasts need colliders..
What do you mean they won't work?
i meant triggers not colliders ๐
in C# you don't place you braces like that.
You can. Cozy braces (aka cozy curlies ๐ธ ) are a style for sure. Not one recommended by microsoft, but there are many styles
!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.
yeah but how do i access the value of the slider to set it's text to that? so far i have this
public void ChangeText(float sliderValue)
{
textObject.text = sliderValue.ToString();
}
Like that
like what?
You need to add the method as a dynamic listener to the slider, the method will be selectable twice, choose the upper one:
you might want to add a string format to the ToString method
its completely valid code btw
They meant having the open brace inline instead of on a new line by itself
microsoft recommended tho
where
oh thank you! ๐ i never knew that was a thing
ok
Use the "Allman" style for braces: open and closing brace its own new line. Braces line up with current indentation level.
i see
does switch statements work in unity?
yes
yes
of course
even pattern matching i think too
good, didn't want 14 statements of if and else if lol
var myRes = _aInt switch {
1 => "",
_ => "Default"
}
or
var myRes = "";
switch(_aInt) {
case 1:
myRes = "";
break;
default:
myRes = "Default";
break;
}
idk just researching it atm
probably a better way to handle it if you need 14 cases.
trying to find better way other than if < else if < else if <etc <else
5 would be fine for if and else if right?
sounds like you need a list and a loop
sounds like you need to apply some object oriented programming actually
Hard to say without knowing specifics
if you're at 14 switch statements you're doing something wrong
well
pattern matching turns into if else statements anyway under the hood
I think switch statements are similar too
after X statements it turns into a map
pattern matching is just if else but prettier
I just need to learn basic programming, trying to do that now tho lol
trial and error is the best way i learn things
my python scripts usually do look pretty awful, but when it comes to runtime performance of your games you do want those micro optimizations
today i managed to write myself the entire main menu funcioning script, which i was content to have learned i can do
just trying to push a bit
I really like figma to make UI
Theres a plugin on unity store where it can convert figma designs to Unity components
Lets you worry about just the code when you import into unity instead of fiddling around with UI components trying to position them correctly
||
Can this only be used once?
interesting, i thought so which is why i used it but this is throwing me an error
Thats because you closed it too early
"Invalid expression term"
remove the ) inside GetComponent<Bathroom>())
ohh i didn't notice that ๐คฆ
Note how this is written
if(aCondition() || aCondition2() || aCondition3()) {
if( conditions )
yeah, the conditions have their own brackets
Whats the hotkey to quickly move the code to the intended position?
you highlight and press this forgot what it was
CTRL + K, D
Thanks
foreach(GameObject npc in FindObjectsOfType<NPCScript>()) This gives an error cause it can't convert from NPCScript to GameObject, but how do I make it so it does work? Adding GameObject. to the start of the FindObjectsOfType<>() function didn't work and you can't add .gameObject to the end of it
change 'GameObject' to NPCScript
That's what I did before, but something went wrong somewhere, so I'm just going through and changing things here and there to see if anything makes a difference. Is there no way to get the game object itself from the FindObjectsOfType<>() function?
npc.gameobject
use a simple for loop rather than foreach
.Select(x => x.gameObject) at the end.
im getting kinda used to code and im wondering if this will work. if ("Gorilla Rig") is within 5 of ("Door") play anim ("DoorOpen") then play anim ("DoorIdle")
as written, no
you wait until the door is open before playing door idle
ok so if ("Gorilla Rig") is within 5 of ("Door") then play anim ("DoorOpen") wait until ("DoorOpen") is done play anim ("DoorIdle")
yep, so now translate that into c#
if you don't need them.
don't forget to call System.Bugs = 0 afterwards
it SHOULD work now right?
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
foreach(NPCScript npc in FindObjectsOfType<NPCScript>())
{
if(questProgress.ContainsKey(npc))
{
npc.GetComponent<NPCScript>().Progress = questProgress[npc];
}
else
{
questProgress.Add(npc, 0);
}
}
}```
I'm trying to crate a script that will store some very simple quest data (Progress) when you travel across scenes. This is so that every NPC doesn't act like they see you for the first time whenever you come back from another scene. However, what I've made doesn't seem to work, even though I've confirmed it is storing its values in the dictionary.
It seems that whenever you come back to a scene you've already been in, Unity acts like the objects in the scene are new, since it puts them into the dictionary again even if they're already there from the last time you were in the scene. Am I going about everything here the wrong way? What could I do to possibly make it work better?
really?
npc.GetComponent<NPCScript>()
oh, and if it DOES work, should i attatch the script to the door?
or the door and the player
any idea what could be causing my camera to tilt like this? (Using cinemachine)
Well, unloading a scene destroys everything it it and loading a scene instantiates everything again. So if you script is on a gameObject in the scene it will also get destroyed, including the dictionary.
Well the script with the dictionary is on an object that doesn't get destroyed on load, so that's not an issue. But do you think it would work if I instead used Transform as the key in the dictionary, and used that to see if any object "matches"?
is this working, and should i attach it to the door or the player, ir both?
ive been doing that for the pst 7 hours
Wait is this not a joke
you must have been trolling
I thought this was a joke
not a joke
IM NOT TROLLING
Then you should learn how to write any code
then i would say programming is not for you
TUTORIALS DONT HELP
Like, even scratch would improve this
they do help
Hell you could probably learn more programming reading Moby Dick
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
@cerulean kestrel
thats pretty funny, but
no one will even read that
I'm not downloading a random file
ik i was jokin
anyone knows why i cant reference my scritpableObject?
show the definition of the scriptable object class
Unity already uses the Main function...
You would never use it yourself
Don't make a class called Program
The whole if line is not c# at all, it's just psuedocode
Basically nothing here is even close to right
Delete it all
ok ill go to gen
go through some very basics C# tutorials
then go learn basic of Unity
Do you have a class called damageType?
in case you missed it, "System.Bugs = 0" was a joke.
oh
That checks out, what does the error say?
any compiler errors? did you save? is the file name same as damageType?
i just wanna know if it works
this is not a code suitbale for unity
This is not code this is fantasy
how do i make it sutiable
it says teh namespeca dotn exit
This is, at best, pseudocode
i already told you
This has nothing to do with C#.
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
By learning how code works
Using the links provided
blah blah blah ok back to tutorials see u in seven years
Yep have fun
Is "Behaviour Designer Tactical" a third party asset?
Perhaps it includes an assembly definition to bundle all of its code together.
still its the namespace not existing, but it obviously exist
Does your project use assembly definitions
Don't put your own code into the asset's folder. Put it somewhere else.
it doesnt say that
it says type or namespace
If I'm correct, then all of the scripts in that asset are bundled together. They are compiled separately from the rest of your code.
So they can't see your own classes.
This isn't normally an issue, because third-party assets would have no clue what classes exist in your game anyway
(how would they know?)
what, so i can just copy teh script make a new file paste teh scritp and it works?
Perhaps. I'm not sure what you're doing there.
Are you creating a new node/behavior/etc. for this system?
If you're trying to modify existing code, it won't be so simple.
yeah im customizaing a simplescript tehre
If you want to modify code from the asset, then you can't move the file out of the asset's folder
because that change which assembly it goes into
and any other code that depended on it existing will not be able to see it
yap, changign it to another fiel solved the problem, good thign im still on prototype phase and didnt needed to change to many references
thx for the help
Hey, guys! I want to save my audio settings in options scene when I am in play mode and when I get out to reset them back to default how to do that?
you can use PlayerPrefs
I mean I know how to save my settings but I dont know how to reset them back to default when getting out
there's a method for monobehaviours which is OnApplicationQuit
is a dictionary serialisable?
nope
So, I can use OnApplicationQuit to reset my settings? So, where I have my reset settings method I do have to use that inside OnApplicationQuit()?
yes
@golden otter Does it work only for quit button or whenever I am clicking play mode on the editor?
or for both of them?
if for quit button you mean the close operation on the exported build yes
I mean in my user interface I have quit button, so whenever player clicks that button to get out of the game. I want to have saved settings on my game when I am in and when getting out to reset those settings to default. That what you said doesn't work actually.
I tried to use that OnApplicationQuit() but nothing
if when clicking the quit UI button it calls Application.Exit, theoretically should work
lemme try
i tried to print a log in the console when exiting the application and it works, could you show the relative code?
{
StartCoroutine(QuitAfterDelay());
}
IEnumerator QuitAfterDelay()
{
yield return new WaitForSeconds(quitButtonDelay);
Application.Quit();
EditorApplication.ExitPlaymode();
settingsManager.ResetSettings();
Debug.Log("Game quits and editor play mode stops!");
}```
I have that two methods for quitting the first one is the main method and the second one is the method to quit after a delay for my button to make it look smoother.
the resetsettings should be called before Application.Quit
or you could use the method OnApplicationQuit
Oh you are correct!
That makes sense you cannot reset settings if you have quitted already XD
i generally do hold the coroutine object incase users hit StartCoroutine twice
.e.g.
if(_currentCoroutine != null) {
StopCoroutine(_currentCoroutine);
}
_currentCoroutine = StartCoroutine(QuitAfterDelay());
in your case you most likely dont want to even stop it
but if(_currentCoroutine != null) return;
fyi, doing StopCoroutine() wont make currentCoroutine null
so the user can still start the coroutine multiple time
it should either set the _currentCoroutine to null, or just do
if(_currentCoroutine == null)
{
_ currentCoroutine = StartCoroutine(QuitAfterDelay());
}
this way it will start only once even if the user spams the button or whatever
can you add scripts to an object in code?
myObject.AddComponent<ScriptName>()
I want to make an item system where a player can pick up and drop one item at a time, and if the player drops one item onto another they get crafted into a new item. would this be a good start towards that goal?
dont need to be abstract
you have no abstract methods
!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.
he doesnt need to
abstract is good in this case
as you don't want instantiate or add just Item
i will be making a method where you try to craft
as this will be a base class for other items
but i wouldnt do it as a monobehaviour
you could do it as a scriptable object
sorry, you can have Item monobehaviour
Agreed. Abstract poco would be good here
but also can have SO like ItemData
where you put all the info for the item
name, isStackable etc
Ah fair point
also you should get familiar with serializable dictionaries
game changing tbh
basically, the player will only be able to hold one at a time in their hands, and if they drop one onto the other it turns into another one. thats why i wanted to know if i could add or remove components, because i wanted to, say, remove the ribbon component and add a bandage component
still, doing all the item data in scriptable object will be much easier
and more readable and extendable
and if you want to change the item name, you just go into the scriptable object of that item
and change it there
I do something like this:
https://configapi.dev.kitsumon.net/api/Config/GetCrystalConfig
https://configapi.dev.kitsumon.net/api/Config/GetUpgradableConfig
So i have a base Item class, then have ItemType inside it. It can be CrystalItem or UpgradableItem etc....
To get the definitions attached to class its a API call on startup
Each item is assigned a ID
sounds good, but how would i make the scriptable objects talk to the gameobjects in the game?
abstract class Item : MonoBehaviour
{
public ItemData itemData
// methods
}
then you can acces your item.itemData.itemName etc
yeah yeah
:\
that sounds good
you can also make an interface for the Items @stuck palm
Dont use public ItemData itemData
ICraftable for example
firstly your naming convention for public fields is incorrect, secondly public fields are not advised in c# convention
Whats ๐ค about this. Where in software do you see people using a load of public variables
naming conventions are up to him
Use a property over public variables
he doesnt need to follow the advised c# conventions
thank you this is good, my brain cogs are turning now LOL
he can use whatever he wants ๐คท
And also Pascal case any public variables
np lmk if you need any more help
Im only advising as per guidelines
please re-read
better teaching the correct way than doing it wrongly
how you are doing
we need more people like you ๐
yes and less like you teaching people to write public variables in their systems
i think public is necessary in this case because when the items interact they have to look at each other's data
i didn't teach him anything dude
You can use internal for this
i just adapted tto his code
If you want to serialize a field or property you can use the following:
[SerializeField]
private MyObject _myObject;
Or property:
[field: SerializeField]
public MyObject MyObject { get; set; }
why use unity at all?
i just guided him based on his code and actually helped him, instead of moaning like you, please cut the talk
just code ur own engine
yea
This way you can have a public property
Hi, I'm having this problem using NavMeshPro :
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
Here is my class
using UnityEngine;
using UnityEngine.AI;
public class PhantomScript : MonoBehaviour
{
private NavMeshAgent agent;
[SerializeField] Transform target;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
agent.isStopped = true;
}
private void Update()
{
agent.SetDestination(target.position);
}
}
And there is my object :
did you bake the navmesh?
yes
and is your agent placed on actual navmesh?
what does it means ? ๐
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
agent.isStopped = true;
Are you sure isStopped = true is not causing a issue?
show me the object in the scene view
code has nothing to do with this issue
and where's the agent? this red dude?
yes
did you import the navmesh 2d package
or 3d one?
is the game 2d or 3d
if it's 2d you need NavMeshSurface2D
attached to the surface
Yeah but I'm using NavMeshPro not the Unity one
I followed this tutorial :https://www.youtube.com/watch?v=HRX0pUSucW4
GitHub project for 2D Navmesh pathfinding:
https://github.com/h8man/NavMeshPlus
Join the discord server: https://discord.gg/EFrYczuAwc
then i have no idea if this asset supports 2D navmesh
why not just use the unity built-in one
Yeah thanks you
- How to create 2D AI pathfinding using the Unity NavMesh components!
- How to have 2D NavMesh Agent in Unity 2022!
GitHub Link: https://github.com/h8man/NavMeshPlus
And don't forget to subscribe for more! ;)
It's the same lib he's just using an older version
no he's using a 2D package
and the asset you have probably is made for 3D only
if there is no NavMeshSurface2D component
@thorn fossil try to remove that isStopped = true and see if it works?
dude that has nothing to do with it
The changeDestination docs clearly say navmeshagent should be active
Nothing hurts in enabling it
and seeing if it works
SetDestination()*
Check the description of the video I sent you Its' the same lib
its not
he's using NavMeshPlus downloaded from github
not NavMeshPro from asset store
"com.h8man.2d.navmeshplus": "https://github.com/h8man/NavMeshPlus.git#master"
This is from my manifest.json ...
you said you are using NavMeshPro
I miss named it :/
!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.
are you sure that OnTriggerEnter is called at all?
anyway, your collider is not set to isTrigger
yea when i pressed e on the book it goes little far
and touches it
does your player has collider with isTrigger and a rigidbody?
put a debug log in the ontriggerenter to see if its even called at all
I found why it was buggy, the pos Z was like so far away from everything else ๐
It was just that
nice!
!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.
Ive made a moveable character on 3d, i used my own script didnt use charactercontroller, so I can walk on the default Terrain unity provides but when I create a 3d square object to test, my player wont move at all
I do have rigid body on my player, the square also has box collider any ideas ๐ค
oh sorry i tought you answered me lol
probably missing a Ground layer?
yes check if the OnTriggerEnter is called at all
because i doubt it, your collider is not set to isTrigger
please
