#💻┃code-beginner
1 messages · Page 590 of 1
im using player input manager but i dont think thats the problem
It demonstrably is your problem. If you're clicking one time, then your screenshot proves this is the case
You're getting multiple logs stating the click was detected
so there's multiple things running that line
would holding the button affects it ?
No idea. Depends on what getClicked does on NewVirtualMouse
Unity has no components named NewVirtualMouse so I literally cannot know what that function does
How about replacing the log with a better one:
Debug.Log($"{gameObject.name} has detected Mouse clicked", this);
no need
i hold press it and got jambo log
so its a hold problem probbly
`public void OnClick(InputAction.CallbackContext context)
{
Clicked = context.ReadValue<bool>();
//Clicked = context.action.triggered;
if (Clicked)
Child.GetComponent<Image>().sprite = clickCursor; // שינוי תמונת ה-Child
else
Child.GetComponent<Image`
hi, in my game u click tiles to "damage" them. when their health reaches 0, they start healing. however for some reason, my tiles don't ever heal their hp back past 25
checking if tile needs a heal: https://hastebin.skyra.pw/cuhasiyipa.csharp
tile heal logic: https://hastebin.skyra.pw/ibiyepelok.csharp
is it readvalue for 1 press ?
Try logging health and maxHealth after you add health. See if they're what you expect
I think it depends on what your action type is for that mapping
okay, i've logged it and it said
"health :125 maxhealth: 100"
which is weird because i dont thinkt he health should be above the maximum and i dont know how its setting it to it's current health + 100
Your 2nd script has formatting errors. I can't properly read it. Place some logs to make sure the code reaches certain parts . . .
Well, your condition runs if the health isn't greater than max, dmso if it's at 100, then it'll add 25 to it then stop
you set health = Maxhealth after the loop. Log after that line to see if it sets back to 100 . . .
okay, ive logged it and it sets it back to 100
ive rewrote the line so that it is health <= Maxhealth instead of health < Maxhealth but for some reason the health is still being set to 125?
public void Heal(float value) => CurrentHP = Mathf.Min(CurrentHP + value, MaxHP) if it's of any help, this is how I have my own healing code that makes sure it never exceeds the max value
Mathf.Min will return whatever is smaller, so if given (125,100) it would return 100
the Min and Max functions are quite helpful for logic like this
I think part of the problem youre having is while (health < Maxhealth). If health = 100 and MaxHealth = 100, then the condition will enter because health is not actually less than the max
health gets to 100, then heals by 25, and only now will that condition no longer be met
yes, i changed the line but the issue still seems to be occurring. its hard to describe but even on the first loop of the while loop the health gets set to 125 and im not sure how, the health should just be 25 if that makes sense?
can you post the Update code again? the original one has errors and format issues . . .
Yeah. Oh, wow. This one is completely different than the original posted code . . .
oh sorry its the same code it just copy and pasted weird idk why
i see what you mean now
I think the issue is that tile.Heal() runs multiple times. In Update you check if its health < 0, but the coroutine doesn't add 25 until after 2 seconds. Update runs every frame, so . . .
yes, i think that seems to be the issue ive been trying to avoid. i think ill just seperate my logic form the update loop completely. thank you for the advice!
also, you can use a bool to check if the tile is already healing and check that. If it's healing, then skip it and continue the loop . . .
I would do that by assigning a Coroutine variable to StartCoroutine(Healing()). At the end of the coroutine method, assign the coroutine variable to null. Create an IsHealing get-only property that returns if the coroutine variable is not null, and check that property instead of the tile's health . . .
if I disable an object via script, then reactivate it, will the scripts inherited to the object come back working too or not?
EDIT (I read it wrong): When you enable a GameObject, any component attached will OnEnable and continuing ruining Unity lifecycle methods . . .
Scripts aren't inherited to GameObjects (that was my confusion). They are separate components attached to a GameObject . . .
Basically, a GameObject is a container storing a list of components; that's it.
sorry, one last thing, how can i skip an iteration of the loop and go to the next one if the tile IS currently healing?
No prob. Search: "c# skip loop iteration" . . .
okay thank you, i see it now
ok i am having an issue. i got this script to turn on and off my flashlight. i also have a script on my player to not destroy my player nor flashlight. my flashlight will work in the first scene, turning on and off. but when going to my second scene my flashlight is still on my player but the script to turn it on and off no longer works
first scene it works
how do i fix?
You can't use yield instruction unless it's a coroutine
You can't have yield in the method. The error says no iterator block is allowed . . .
The method returns a void its not a IEnumerator cannot return a yield
Strike three, you're OUT!
so how do i adda cooldown to a hitsound?
switch it to a coroutine? or make a timer in Update
Create a coroutine and call that inside of the trigger method . . .
How are you preventing them from being destroyed? DDOL?
Is the flashlight a child of the player? What object is the ToggleLight script on, what does your hierarchy look like?
uhh what do i acc put and where do i put it?
the flashlight and script are both childs of the player
which is weird because the flashlight stays and so does the script
but the script no longer works??
What GameObject is ToggleLight attached to?
exactly. ddol
ToggleLight is attached to the flashlight, which is a child of the player
which the ddol script is attached to
And LightSource is a child of the flashlight?
yep
When you are in a new scene, look at the ToggleLight script from the inspector. Is the LightSource GameObject empty or does it have a reference?
okay i just fixed it actually. so apparently the flashlight script was working but I just needed to move the light forwards a bit because it was stuck in the flashlight?? but it worked in the first scene...
thank you though haha @cosmic dagger @verbal dome
i was stuck for like 20 minutes
how do i makea timer?
using Time.deltaTime or Time.time, you can google them as they have been done and redone to death
I would swap IStateInteractable to IInteractableState and change IInteractionList because you're not storing an actual list but an array. You can use Collection, Group, or Set instead . . .
IInteractableCollection : IInteractable
IInteractableGroup : IInteractable
IInteractableSet : IInteractable
does sound better.. 1 sec let me get this switch script saved and in tested
Works thanks
needed something to give my Switches a bit more info to them..
so w/ teh Description and the Hint i can use UI popups w/ each switches name, etc
got 1 script doing lots of stuff 😅
can u expose a nested array in the editor??
how do you make a class singleton
https://unity.huh.how/references/singletons this one also has good info like how to make a generic so you can make easy singletons
then u can simply use : Singleton<YourScript>
extremely helpful as long as u dont go crazy with em 🤪
dont crosspost
i wanted to save all the things that changed in my scene during gameplay so i thought id use loadscenemode.additive to load the minigames
however the scenes intercept eachover so it becomes a mess
Yeah, that's what additive scene loading is, it adds the new scene to the current one
so i have to make the static class singleton somewhere
and then I can use it?
yes, so what should i be doing instead
i can disable the scene?
Well, disable components of the scene that would be causing problems, because why would you use additive in the first place if you wanted to remove everything
if i could set the scene to inactive then it would keep all the changed stuff the same for when i want it
Not sure if you can just deactive a scene as is, so you may need to throw everything into an empty mono behaviour and deactive that
I wonder what you wanna save in playmode that you dont have access too in edit mode. Values on a script?
removed objects need to stay removed and values need to be kept
So you are doing your level setup in playmode or what exactly?
the player can pick up objects which then get removed from the scene
Anyone know how can i access this RectTransform option via code? (when you press left alt to stretch)
you're setting a combination of anchors, pivots, and positions when you click these presets
That would be anchorMin and anchorMax. These buttons just set those values to different combinations of values
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RectTransform-anchorMax.html
i tried something like .GetComponent<RectTransform>().anchorMin = new Vector2(1f, 1f);
nothing happened tho
Wait, so you want the scene to be saved in runtime? Not when exiting playmode?
Once you change the anchors, you'll need to also change the anchoredPositions
I'm pretty sure they just want the changes to remain for when the player goes back to the scene. This isn't about actually saving a scene file
when i load a scene for a minigame and then leave the minigame the original scene is then restarted
yeh, I just realised that 😄 I thought it was about scene state in playmode being restored in edit mode. My bad
So you need to come up with your custom solution like having a save file for the user and on scene enter, let the scene save file overwrite whatever you want to overwrite in your scene
You could put everything in the scene as a child object of one shared parent, and when you lod the next sceen additively, you can disable that object to disable everything under it
This is assuming you have no functionality that depends on OnEnable or OnDisable
I have decided to include the mini games in the main scene as under a parent object each
I did think of that but don’t know how I will re activate the map afterward
Objects that are disabled can still run functions you've defined. You can have whatever object is supposed to change back to that scene reference it and re-enable it. You'll need some way of getting a reference to it, probably the easiest way would be to make it a singleton, but that assumes there will only ever be exactly one scene that needs to be "paused" this way
when I use "this" in the script it returns the object as a GameObject or Transform?
It returns the script
oh ok
my hierarchy is gone help
thx
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
So, ive been trying for a while to make my player be able to jump only when he is grounded. Now this code works on another map that I have tried but for some reason doesnt work on another one. Ive used debug logic to figure out that the issue is that i am not being considered "grounded" when I should be i have tried adjusting player settings, tweaking the way detection for being grounded works but nothing is working. I also made sure that the layer mask of "whatIsGround" is applied. Would really like some help on this issue:
A tool for sharing your source code with the world!
I need help with a script, the script keeps falsely detecting exit collisions, script:https://paste.ofcode.org/p7FkB2t25WDbtbwszwySMr
Before your grounded raycast, add this snippet:
foreach(RaycastHit hit in Physics.RaycastAll(transform.position, Vector3.down, PlayerHeight * 0.5f + 0.2f)){
Debug.Log($"Raycast detects object {hit.gameObject.name} with layer {LayerMask.LayerToName(hit.gameObject.layer)}, Passes mask? {whatIsGround == (whatIsGround| (1 << hit.gameObject.layer))}");
}
It's going to absolutely spam the console, so you might want to turn on Collapse if it's not already on
What do you mean by "falsely detecting exit collisions"?
Any time this object stops contacting an object tagged "Floor" it will fire that condition
For more info this piece of code is in the player script: if (!IsGrounded)
{
transform.position += new Vector3(0, Time.deltaTime * -10, 0);
}
So i try walking in the game and and i start falling in the map
Does this error matter or not?
Assets\Scripts\PlayerMovement.cs(46,183): error CS1061: 'RaycastHit' does not contain a definition for 'gameObject' and no accessible extension method 'gameObject' accepting a first argument of type 'RaycastHit' could be found (are you missing a using directive or an assembly reference?)
You're right, I was freehanding this without intellisense, forgot that it doesn't have a .gameObject, swap those out for .collider instead
alright
Assets\Scripts\PlayerMovement.cs(46,188): error CS1061: 'Collider' does not contain a definition for 'layer' and no accessible extension method 'layer' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)
bah, never code without an IDE kids. .collider.gameObject.layer for those
Wait are you modding baldi?
Because it has a PlayerMovment script
PlayerMovement is a pretty common thing to name a script that moves a player
Okay
So i just tried it and im not getting any debug logs. just to make sure, this is the line I wrote:
foreach (RaycastHit hit in Physics.RaycastAll(transform.position, Vector3.down, PlayerHeight * 0.5f + 0.2f))
{
Debug.Log($"Raycast detects object {hit.collider.name} with layer {LayerMask.LayerToName(hit.collider.gameObject.layer)}, Passes mask? {whatIsGround == (whatIsGround| (1 << hit.collider.gameObject.layer))}");
}
does canvas object covering entirety of other objects turn them inactive?
Then that would mean that there are absolutely no objects within range of that raycast
Regardless of layer
How is that possible if I am standing on a floor?
debug drawray your raycasts
Possible that the raycast isn't where you think it is.
Is there any way to visualize a raycast?
yes drawray
I checked btw, if im free falling, I get this log|
Raycast detects object PlayerObj with layer Default, Passes mask? False
UnityEngine.Debug:Log (object)
PlayerMovement:Update () (at Assets/Scripts/PlayerMovement.cs:46)
but nothing if I am on something. even a new p[lane
Okay, so the ray hits the playerObj, but nothing else
you mean like creating a new layer mask just for the player? and making the raycast hit that instead of my ground later?
oh ok that makes sense, that d instead of s confused me
Sorry, typing on my phone
Is playerHeight the value you think it is?
ill try and figure out this Draw Ray thing
bruh its at 0 when I set it to 0.5 earlier
im sorry ill try again
bruh i think i fixed it
my player height was too low.....
For some reason, it needs to be at lesat 2.8
but on another map, I can go as low as 0.5
sorry, just need a link to the !cs server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Anyone knows how else am i able to edit script? I clicked on it but nothing opens up, i also changed unity > preferences to VS code but am still unable to open a script
can i set negative time for audiosource
hi
You could open the script in the project window
im getting this but i dont know if its "me" issue or it supposed to not work that why i ask here
C:\build\output\unity\unity\Modules\Audio\Public\sound\SoundChannel.cpp(345) : Error executing result (An invalid seek position was passed to this function. )
Ive opened but how do i edit it tho? it seems like im unable to edit or click on it. Sorry im a beginner
Hey, can you help me with this? I have 2 codes that I want one to connect to the other, the one that is going to be connected I want to make it not do anything when the other is being used and when it finishes using the other code it goes back to how it was before.
public class MoveAndRotate : MonoBehaviour
{
public float moveSpeed = 5.0f; // Velocidad de movimiento
public float sensitivity = 3.0f; // Sensibilidad del mouse
public float minY = -80f; // Límite inferior de rotación
public float maxY = 80f; // Límite superior de rotación
private float rotationX = 0f;
private float rotationY = 0f;
void Update()
{
// Movimiento con WASD
float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; // A/D
float moveZ = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; // W/S
Vector3 move = transform.right * moveX + transform.forward * moveZ;
transform.position += move;
// Rotación con el mouse (solo si se mantiene presionado el botón izquierdo)
if (Input.GetMouseButton(0))
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
rotationY += mouseX; // Rotación en Y (izquierda/derecha)
rotationX -= mouseY; // Rotación en X (arriba/abajo)
// Limitar la rotación vertical
rotationX = Mathf.Clamp(rotationX, minY, maxY);
transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
}
}
}```
so when you double click the script , does VSC open ?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Nope
Use Scriptbin to share your code with others quickly and easily.
you tried restart PC maybe ?
Ive restarted but doesnt seem to work. My VS code seems fine too
close VSC if its open, click Project files and open script again double click
still doesnt work. am i supposed to drag the file into VS code?
Hey, can you help me with this? I have 2 codes that I want one to connect to the other, the one that is going to be connected I want to make it not do anything when the other is being used and when it finishes using the other code it goes back to how it was before.
public class MoveAndRotate : MonoBehaviour
{
public float moveSpeed = 5.0f; // Velocidad de movimiento
public float sensitivity = 3.0f; // Sensibilidad del mouse
public float minY = -80f; // Límite inferior de rotación
public float maxY = 80f; // Límite superior de rotación
private float rotationX = 0f;
private float rotationY = 0f;
void Update()
{
// Movimiento con WASD
float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; // A/D
float moveZ = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; // W/S
Vector3 move = transform.right * moveX + transform.forward * moveZ;
transform.position += move;
// Rotación con el mouse (solo si se mantiene presionado el botón izquierdo)
if (Input.GetMouseButton(0))
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
rotationY += mouseX; // Rotación en Y (izquierda/derecha)
rotationX -= mouseY; // Rotación en X (arriba/abajo)
// Limitar la rotación vertical
rotationX = Mathf.Clamp(rotationX, minY, maxY);
transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
}
}
}```
https://scriptbin.xyz/okuyawapow.cs
Use Scriptbin to share your code with others quickly and easily.
Unity is supposed to open VSC and the script
if you can help me?
Sounds like you just want to enable or disable the components as you want them to be functioning or not
public int value { get;set; } I read somewhere before that we can show this prop in the inspector.
how to do that?
Add [field: SerializeField] before it
That will apply the [SerializeField] attribute to the hidden backing field of the property
thanks
yes that's how it is
2 codes? As in scripts? What's your other one?
Oh wit didn't see someone else responded
I want the one in the link to connect to the one written in the message about which the message is written. I want to set it to deactivate and reactivate when nothing is being done with the other one.
uno q habla español, que copado
si
Give that script a reference to the one you want to disable. Call .enabled = false when you want to disable it, and .enabled = true to re-enable it
Where do I put that in which part?
Wherever you want to enable or disable it
Im making a turn based combat system and I currently have a function that activates a skill (which is a scriptable object that SkillScriptableObjects controls the data from) If i want to have multiple skill slots instead of 1, how should i go about making it? Do i make a class that stores all the ui elements and the Skill? Here is what im using right now ```cs
public SkillScriptableObject skill;
public TextMeshProUGUI nameText;
public TextMeshProUGUI descriptionText;
public Image attackIcon;
public TextMeshProUGUI mpText;
public TextMeshProUGUI healthText;``` ```cs
public void onSkill(BattleStateManager battle)
{
bool noMp = StartBattleSpawns.playerUnit.TakeMp(skill.mpCost, battle);
if (!noMp)
{
Debug.Log("Not enough MP to use the skill!");
return;
}
bool isDead = StartBattleSpawns.enemyUnit.TakeDamage(skill.attack);
battle.hpSlider2.value = StartBattleSpawns.enemyUnit.currentHp;
battle.playerMp.text = StartBattleSpawns.playerUnit.currentMp.ToString();
battle.mpSlider1.value = StartBattleSpawns.playerUnit.currentMp;
battle.playerHp.text = StartBattleSpawns.playerUnit.currentHp.ToString();
battle.enemyMp.text = StartBattleSpawns.enemyUnit.currentMp.ToString();
battle.enemyHp.text = StartBattleSpawns.enemyUnit.currentHp.ToString();
if (isDead)
{
battle.SwitchState(battle.endBattleState);
}
else
{
battle.SwitchState(battle.enemyTurnState);
}```
Make an array/list much like an inventory
Ic, i was wondering if that was the right approach since this is in a state machine (didnt know if it was a good idea to import onEnterState(BattleStateManager battle, BattleStateManager.SkillData skillData)
I mean all you really need are more references to more instances of skills, you can even bind them to some central manager script then bind each one explicitly to some input key or using UI buttons
public class SkillManager : Monobehaviour
{
[SerializeField] SkillSO skill1;
[SerializeField] SkillSO skill2;
[SerializeField] SkillSO skill3;
private void Update()
{
if(Input.GetKeyDown(Keycode.Alpha1)
{
UseSkill(skill1);
}
else if(Input.GetKeyDown(Keycode.Alpha2)
{
UseSkill(skill2);
}
else if....
}
private void UseSkill(SkillSO skill)
{
//Do stuff
}
}```
Here's a crude idea
Hello! It's my first time trying to use UI to pause a game. I have a small game for a jam a guy and I put together and I'm trying to get the menu working.
I have a UIManager empty with this script attached: https://pastebin.com/HED8sJcQ
I've assigned everything in editor. The game is just supposed to sit in the background paused until the person hits play basically. I can hover over my button to see it but clicking doesn't do anything. (It actually makes my character attack in the background).
The game starts in the background before you click play and my Debug.Log in ShowStartScreen isn't ever printing.
I'm not sure what I'm doing wrong here, any help would be greatly appreciated.
what is it asking for?
Ignore the first parameter and just add the type to the component there
For next time, you have to wrap InteractableObj in typeof() so it uses the type correctly. Even better would be to use the generic type.
TryGetComponent<InteractableObj>(out info);
Considering it can also fetch the type from info since it's predefined, the solution of Mao also works.
Some of my UI is being updated on load, but my start function isn't ever being called. I'm so lost on this one.
What do you believe happens when you zero out the timescale?
I believe anything that happens in Time.deltaTime won't move.
Your update loops are effectively frozen there, so any input polling will not be received
This shouldn't affect the UI though right? But regardless my timescale isn't getting set to 0. Which is what I'm confused about.
I'm actually more confused now than I was when I posted because my start function isn't being called, and this is the only script I have that attempts to set timescale so it shouldn't be paused anywhere else even if it affects UI.
Buttons linked to methods like that should probably still be called, but maybe I'm blind but I'm not seeing any here
Oh yeah I see them
Yeah those should still work
I'm actually not sure if start will be called if it's scaled at 0 on instantiation
Start is called on the first update of the script
I had a variable reference to an unimplemented screen tutorialScreen. I commented it out and the line in ShowStartScreen(); and it's working now.
I had no warnings, errors or anything. I didn't realize an unassigned reference in editor could break your script like that. Wild.
I THINK it's solved for now though at least. -2 hours lol. At least I'll remember this 🤷 next time.
I am 💯 you would have gotten an error when accessing a null object. Maybe you just disabled warnings and errors in your console window
Because every null error will break your entire runtime execution. Thats just how it is. So either be sure its there or check for null and skip accessing it if its null to avoid breaking your runtime
lmao You don't have to call me out like that. 🤣 This revelation has lead to me figuring out why my navmesh enemies weren't consistently running their code. They were being killed when they would somehow get off their navmesh and it just causes the code to not run.
I super appreciate that explanation though. It's good to have it put into words.
Not calling out, just pointing out facts, that you might have missed a step in debugging it and therefore I gave the explanation what happens when accessing the refrence not set. Sorry, if that sounded harsh for you, wasnt meant to . I am just a fan of clear words to describe 😄
When should I create manager classes? For example should I create MovementManager, AttackManager, TurnManager, ItemManager, if I'm doing a turn based game?
So, when modifying scale for a sprite, I can't make it tile with the transform component? I need to actually get and modify the ''spize'' component in the sprite renderer?
you can use transform.scale to scale a sprite renderer just fine. can you explain better what you are trying to do?
nvm fixed
using scale doesn't tile it
it just streches it
I just modify the sprite renderer.size instead and it works
You should probably use state machines over Monobehaviour scripts
If your code has allot of if statements, or logic you dont want to get checked every frame
Though if its a very simple system then it doesnt matter
On another note, I want to rotate a sprite between two mouse click such that the ends of the sprite are between the clicks
I converted the mouse clicks Screen to world point
and I get Vector2.Angle
and set the Z rotation to it but it doesn't work. How come?
{
Vector3 Move = new Vector3(0, 0, transform.position.z + 0.1f);
transform.position += Move * Time.deltaTime;
}
This is my code, i know its not optimal but after some time my gameobject dissapears and id like to know why that is. im using 2D
Define "disappears"
Destroyed or just moves out of view of the camera?
Also, if you're working with 2D, you usually don't want to move on the Z pos (in / out of the screen)
2D moves on x/y
I believe that this was it
I haven't made anything 2D .. but I assume Z pos is pretty much ignored
it's used for sorting and depth. and if things get too close to the camera or behind its position then it won't render those objects
plane draw distance, same as 3d
thought sorting was done with the layer field on the sprite renderer
that's just part of it https://docs.unity3d.com/6000.0/Documentation/Manual/2d-renderer-sorting.html
hey guys im implementing a screenshot system where the user can download an outfit that they have created
right now i have a UI canvas that pops up with their outfit and a download button
whats the best approach to making it so when they click download, it locally saves that UI canvas as a png
how can this cause this error
if its null it just gets set to null no?
here is the whole bit if that matters:
item is null there
image or item is null
image is null in the else statement too so no matter what it's going to throw
I had only looked at the first screenshot
it's the only explanation so it is right
prove it to yourself and log it
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
yes but this code is in a foreach Item item loop
Debug.Log($"item is null {item == null}");
so if item is null it cant run
A tool for sharing your source code with the world!
right because accessing a member of a null object is going to throw a null reference exception
itemList can have empty (null) elements
oh does it not throw it if the object itself is null?
it only throws if you try to access something on a null object. you can pass null around all you want, but as soon as you try to get something from that null object it will throw
i see, thank you! ill add a null check and return from the list method then
Do anybody know how components work after initialized?
I keep trying to declare them and assigning some variable to them in the same frame but sometimes it work and sometimes it doesnt, gameobjects also dont seem to work the frame they are created. The variables often seem to be overwritten...
show relevant code
Use Scriptbin to share your code with others quickly and easily.
the loop is ran each update
tree ID does not change
why would it change? you're assigning its current value?
oh no i just did that for a breakpoint
its just that, for some reason the assigned value of a gameobject.... doesnt assign properly?
can you be more specific about wtf you mean by that
:)
I will just trial and error then
thanks for your help
alright, well for future reference, if you cannot actually explain what is happening you're gonna have a hard time getting help. see #854851968446365696 for what to include when asking for help
hey guys new here just wanted to know why my dash only happens once every 3 or so console prints
do you plan on providing context?
ok, heres a simpler way of putting the question
the if statement returns false, What im trying to figure out is if the component has to "initiaize" before actually able to be read?
did you actually save the code? because it's unsaved in your screenshot
in my actual code its scattered in a few places, I just wrote some new ones for an example
but you are right, i will test this first.
sorry for that, i made a dash script with a coroutine and then called it to a player controller. this is vector 2d with 8 directional movement. i did a print on the coroutine and the code works fine, but the actual dash only happens once every 3 console prints
if that if statement is false normally then whatever cur is does not have an InteractableObj component on it. the code you just showed would work
does it matter if the gameobject is active or not?
no
what am I doing wrong here? I thought this was how namespaces worked
are they in the same assembly
oh maybe not
youre prob right ill take a look at that
this made the character dash once in 4 tries
and where do you call dashActive and have you actually done any debugging to find out the state of the variables you are checking to even start the coroutine
dashActive is called in a separate playercontroller and im not sure what youre talking about for the second one
please share all of the relevant !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
FYI you can simplify these three lines.
var info = cur.AddComponent<InteractableObj>();
No point in adding the component just to try and get it when AddComponent can return it (The TryGet here makes no sense either because you literally just added the component, so it's guaranteed to exist).
using UnityEngine;
using System.Collections;
public class Dash : MonoBehaviour
{
private Rigidbody2D rb;
private bool canDash;
private bool isDashing;
public float dashSpeed = 200f;
public float dashDuration = 0.2f;
private float dashCooldown = 1f;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
canDash = true;
}
public void dashActive(Vector2 movementInput)
{
if (Input.GetKeyDown(KeyCode.Space) && canDash && movementInput != Vector2.zero)
{
StartCoroutine(DashCoroutine(movementInput));
}
}
private IEnumerator DashCoroutine(Vector2 movementInput)
{
print("Couroutine start");
canDash = false;
isDashing = true;
rb.linearVelocity = movementInput.normalized * dashSpeed;
yield return new WaitForSeconds(dashDuration);
isDashing = false;
rb.linearVelocity = Vector2.zero;
yield return new WaitForSeconds(dashCooldown);
canDash = true;
}
}
//
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private IsometricMovement Movement;
private Dash isDashing;
void Start()
{
Movement = GetComponent<IsometricMovement>();
isDashing = GetComponent<Dash>();
}
// Update is called once per frame
void Update()
{
Movement.Move();
Movement.Animate();
isDashing.dashActive(Movement.MovementInput);
}
}
yea my problem was that some components are not "responding" after creation, as if they needed a frame to initialize before being set. For example, I tried setting the transform position of an object on start, but it did not move.
okay, now you need to verify that the conditions you are checking are actually what you expect them to be. verify by either using the debugger to inspect them during execution or use logs to print the information
I am not certain on how it works but it could be that Unity needs a frame for these things
Though I believe it always happens at the end of a frame
So it should work fine regardless
Not sure what not "responding" is though
seems to me that everything is working except for the linearvelocity which makes the actual character dash
how have you confirmed that
i printed if the boolean is true or false every time
sorry if thats a dum move
im kinda new

public class peterscript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapiness;
public score score;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
score = GameObject.FindGameObjectWithTag("Logic").GetComponent<score>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) == true)
{
myRigidbody.linearVelocity = Vector2.up * flapiness;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
score.gameOver();
}
}
why do i get this can someone help me?
im new
What does the script that has score look like?
using Unity.VisualScripting.Dependencies.NCalc;
using UnityEngine;
public class pipehotbox : MonoBehaviour
{
public score score;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
score = GameObject.FindGameObjectWithTag("Logic").GetComponent<score>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
score.addScore(1);
}
}
}
i think its this one im not really sure
sorry
i was following a tutorial but i named things differently
how do I trigger the Animator components of an array of GameObjects?
oh wait nvm got it
@lone viper Do you have a score class?
also you should get into the habbit of having good name structure it will be very helpful for you in the future
gotcha
whats a score class
create a seperate script that handles score are you watching a tutorial?
how do I make this work?
yes
in this script you're trying to call score with "score.gameOver();" but as far as I'm aware you don't have a method for score youv'e only declared a variable for it
basically, how do I turn a void into boolean?
there shouldnt be any missing script since this is all theyre doing in the video
Follow what they're doing then but name things properly but as of now you're trying to call score.gameOver but you don't have a method for it thats why you're getting an error
you probably missed something in the video
oke
if (boss.activeSelf)
{
boss.SetActive(false);
gameObject.SetActive(false);
}
}```
is this bad practice in any way? was getting annoying ondestroy errors in unity when quitting playmode
the Application.isFocused made the errors go away unlike Application.isPlaying
You know isFocused is not just false when exiting the editor
So this creates an edge case
That said, XY problem, why do you have these problems to begin with?
It's not really a problem, it's just that it's a team project and I don't want someone to look for a "false" error
I don't understand why there is no option to ignore closing playmode on OnDestroys to begin with
That sounds more like a problem with your code than OnDestroy
What exactly are you trying to do that warrants some OnDestroy not being called when the object is destroyed?
it is meant to be called when its destroyed
while the game is running
not when it closes in the editor
but closing the game in the editor is also destroying all your objects
since you are effectively "closing" the game
sure. but what is the point of that behaviour? what is the use case for OnDestroy triggering when the game shuts down
it feels counterintuitive
OnDestroy triggers when the scene the object belongs to is closed
Closing the game down completely also triggers that since you are unloading the scene
i know
I don't see how that's counter intutive is what i mean
OnDestroy -> when you destroy this object, do ...
Calling the function you use for in-game stuff when closing the game is weird
why not separate the two
unless there is something else that works just like OnDestroy that i dont know about
So you don't want it to show as you're working on it with other people and they might get confused ?
I think the main idea to keep them the same is that whatever you do in editor/build will behave the same
maybe you are looking for OnDisable
essentially yeah, i can also put a comment in but why would Unity throw an error
does that also trigger on destroy?
what is the error by the way?
yeah that's probably a better question
I don't see why this behavior is not expected, when the scene is destroyed, the object is destroyed
doesn't really matter if the game is closing or not
I'm guessing the error is that your PopulationManager.Instance is already destroyed
"Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)"
and it refers to the PopulationManager
then most likely the instance was already destroyed and you're creating a new one, since it's a singleton
sure but my issue is - how else am I meant to call something when the object is destroyed
What happens inside RemoveMeFromPopulation
removes the object from list and decreases populationcount by 1
the error is caused because its a singleton and a new one gets generated if its destroyed but the method is called
you can work around it by storing a reference to the singleton in the class that is being destroyed
Oof, that's tricky
instead of accessing the Instance every time
how do i call something on when its destroyed though
I think in this case you'd be better of adding/removing to population manager in OnEnable/OnDisable instead
the singleton doesnt matter
that works exactly the same and causes the same error
True but then they would be potentionally accessing a destroyed instance of the singleton and getting an object destroyed exception or whatever it is called
he's already checking for null there
although incorrectly, since accesing the Instance property will always create a new one
If it's okay that its null, then sure
my issue isnt with the singleton behaviour
i dont want whats in OnDestroy to ever trigger on game close
idk if there is a different method for that
Btw Application.isQuitting exists, might be also helpful
there isn't, when your game closes your scenes get destroyed and everything contained also gets destroyed
but the idea is, if the object is ever destroyed by whatever, decrease population size and remove it from population list
And when the whole game quits, you don't care about removing it from the population, correct?
yes
are you sure? maybe some using im missing
i saw this mentioned elsewhere too
Oops, *Application.quitting
(Weird naming convention from unity, usually their bools start with is)
IMO the cleanest way to do this would be to store the singleton reference on Awake/Start and then check for null on OnDestroy
its because its not a bool
its an "action" it seems
this doesn't seem necessary, what issue is this supposed to solve?
had some help from copilot, and thats what ive got after cleaning it up
not causing an error in console when leaving playmode
what error
OnDestroy calls a singleton when game is quit
They were accessing an already destroyed singleton in OnDestroy
And accessing it would create it again, which is not allowed from OnDestroy
which creates a new instance
what's the best option for handling multiple attacks inputs: the old Input class or the InputSystem thing?
you could just not make your singleton lazy load. or give it some method or property to null check it without creating a new instance
i think the point of the automatic instance creation is for it to not cause errors if someone forgets to add it to the scene
the singleton solution we are using wasn't done by me, but a colleague
so I wouldn't want to mess with that
but the issue is that automatic instance creation is not suitable there
most likely the issue would also show up if you unloaded the scene manually
You can still do that, just add an option that does not instantiate it if missing
doesn't that do the opposite from the original intention tho
Such as a property InstanceExists or a TryGetInstance method
You'd use it in special cases like this
either way its basically one case in which its bad, i think its better to just use OnApplicationQuit here
Nothing wrong with that IMO
different question though - how do static variables work? I assumed you couldn't change them at runtime, but clearly in the screenshot I sent that's what it's doing
you're thinking of const. static just means the member is not associated with any instance
ah yes i was thinking of constant
if you ever have any new entities like this, you'll have to remember to clean them up in the same way which feels fragile too
what does it mean in practice that its not associated with any instance? does it mean that if I change it, it changes it for every VikingTracker holder?
that is to say, doing things like this adds complexity and something you can forget repeatedly, whereas simplifying your singletons means you never have to think about this again (you just have to ensure your singletons exist, but obviously you need to do that generally)
that's true, I guess I'll bring it up to my colleague who made the singleton solution
if it was my code I'd dive in but I wouldn't want to touch anything he's worked on myself
that sounded bad lol I meant it's his work so I wouldn't want to change stuff without his knowledge*
totally! and collaboration is important
that's what pull requests are for
true, also helps follow DRY
why communicate direclty when you can throw code at someone?
could anyone answer this pls
u can get the job done w/ either system
Whichever one you want
ok then ty guys
new is better in the long run
i posted this issue im having with my code and got told to configure my IDE. ive followed the steps on the microsoft page called 'Configure Unity to use Visual Studio' by selecting it in my external script editor, updating the visual studio editor package, and updating visual studio but nothing seems to have changed and i still have the same issue. does anyone have any tips or know what to do??
Yeah, it's basically just better in general. The relative value of each system doesn't really change with what you intend to do with that input.
Click "Regenerate Project Files" on the window you set the external editor on
Do it while the IDE is closed, then reopen unity and reopen the IDE
and in case its not your ide and are using assembly definitions, make sure the asmdef is referenced so you can use the type (if in a package, check if that has an asm def defined where this script lives)
sorry i dont understand what you mean (im very much a beginner), could you elaborate?
If you dont know what they are you are probably not using them
https://docs.unity3d.com/6000.0/Documentation/Manual/assembly-definitions-intro.html
Assembly definitions are used to break your code into separate units.
Incorrectly set up asmdefs wouldn't completely break your IDE, though
Do you currently have any compile errors?
Newly installed packages can't start doing anything until you resolve that
i gave up and just changed the code but thanks for the suggestions i do appreciate it :P
Before I get to it and totally waste my time; if I Lerp an object posstion, that does not trigger the trail right?
Trail renderer?
Yes
I don't know why it wouldn't trigger
The trail doesn't know/care if the position was lerped or changed in some other way
Lerp just gets a value some percentage of the way between two other values. It's not a different method of moving an object
It's just a way to compute a value
I thought trail just activates when you move the thing, not teleport it, which is what a Lerp possition would do
All transform-based movement is teleportation
With transform, there's reaally no difference in "moving" and "teleporting"
I'm following the Unity Essentials Pathway on Unity learn and I'm on Mission 4, Step 7. I opened the PlayerController (MonoBehaviour Script) as per the instructions and it's just opened to a blank screen with a toolbar. I'm pretty sure I'm meant to be seeing some starter code but there's nothing. Anyone able to lend a hand?
what I'm seeing
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
make sure your IDE is configured properly
Like this?
yup
try close VS click Regen Project files
double click script again
Does anyone know why when I add a box collider to my tilemap the collider is a big rectangular area and not the individual tiles?
Oh got it
Because a Box Collider is just a box collider. You might want a Tilemap Collider 2D and add it as a new layer
Yea I was looking through the colliders and found it
thanks bro
So I’ll trying to make an auto player for my black jack game but after one card it just stops hitting or it doesn’t stick / press play again and idk what to do lmk if you need the whole script or just this.
It's 2025, let's take proper screenshots https://www.take-a-screenshot.org/
Even better, properly share the !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Is unity's visual scripting still called bolt? Or did they re name it/make a new thing?
trying to get back into learning unity now that i've got time but idk where to begni yet. am looking for visual scripting though
it's just called Visual Scripting now and there's an entire other server where you can discuss it #763499475641172029
ok that's very useful information for me than. Thank you.
Hey guys! I'm learning Unity, I'm at the very beginning.. I tried to do some targets to shoot, but I see them in this way.. Anyone know why? what might cause that? they are simple 3d objects created directyle from Unity
I see them in that way even when I start the game
#💻┃unity-talk not really code question. You have to show your setup
could be graphical glitch? or maybe try creating a new camera object?
I think I've kinda solved it, I had probably a wrong Shader assigned.. changing the shader made it be visible.. I'm still at the very beginning and I actually don't know what's that property for 🤣
Shader tells computer how your object appear in scene, yea as beginner you should not be touching shaders just yet
if you want to change the look just mess whats already inside the material like color / texture
Hey,
Is there a way to check the hitbox of a character midgame?
I mean cuz i added a meele attackbut i dont know how much large it is
Here's the script btw
{
Collider2D hitEnemy = Physics2D.OverlapCircle(transform.position, attackRange, demons);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
}```
you can use the Gizmos class to draw the overlap circle, or use a convenient package like vertx's debugging to draw your physics queries (mostly) automatically
Hi, how do i use Gizmos?
I tried to aply it but i didnt knew how, so what i have to do?
Oh, thanks :3
i dont think i did that right
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
// [class CreateAssetMenu]
public class CharacterDatabase : ScriptableObject
{
//creating the different races into an array
public CharacterSelect[] character
public int CharacterCount
{
get
{
return character.Length;
}
}
public CharacterDatabase GetCharacter(int index)
{
return character[index];
}
thanks
so I'm having an issue where im trying to make a database. after i finished this script and i went back to unity. i right clicked and went to create. and it seems i cant make the character database
the option isnt there i mean
Why would you expect it to be there?
that option is only available when you have a CreateAssetMenu attribute on the class
oh i didnt copy it right
which you have not completed correctly and also commented out
my bad
its not commented out on my script thats weird
Could you guide me in how to complete it correctly?
why not just read the docs?
i meant if i could be pointed there
You can just search CreateAssetMenu on google
or even ScriptableObject because the example for that includes the usage of the attribute
thank you boxfriend
I need the static class GameManager to exist right away. Is this the best way to do it?
GameManager.Init() literally does nothing but print "Game Manager is initialized". But I need to call it in order for the static constructor inside to execute its code at all.
You could use this in GameManager
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
The user has no control on when the static constructor is executed in the program.
A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced.
there is no guarantee when a static constructor is going to be called except that it will always be called before any instance is constructor or any static member is accessed. if you need something to happen before everything else in a static context with no extra code, then use what Osmal suggested instead of relying on the static constructor to be called
Honestly all I'm trying to do
is have a GameManager persist through every scene. Is using DontDestroyOnLoad() better for that? I just feel weird attaching a gamemanager to an object in a scene
but if that's better practice so be it
static constructors and DontDestroyOnLoad solve completely different issues. if you just want it to not be destroyed when you change scene, then yes all you need is to pass it to DontDestroyOnLoad
if you just want to spawn the object and mark it as DDOL any time you launch the game then use the attribute osmal linked to do that initialization
The only reason I used a static constructor is that I want my GameManager to subscribe to events that I plan to fire (like a GameOver event)
With other gameobjects, I use Awake()
but since my game manager isn't a regular game object, I couldn't
but I guess it can be
it doesn't need to be. use the attribute that was suggested
I've never used this type of thing in C#, intruiging
is it some preprocessor thing?
Attributes!
Hey guys! Is there a way to detect if I have only clicked (and released) or if I'm holding the left click with the new unity input system?
[SerializeField] private InputActionAsset PlayerControls;
private InputAction shootAction;
void Awake()
{
shootAction = PlayerControls.FindActionMap("Player").FindAction("Shoot");
//shootAction.performed += _ => FireWeapon(); // When clicked
}
Or do I have to do manually, like setting a variable isShooting to true when performed and to false when canceled?
did you look at the other events?
Use Update if you want to do something every frame
Not events
The events will only tell you when something changes
if you want hold behavior on button set it from Button to Any Value then you can use Started,Canceled to set a bool
Isn't that the point of the new input system? like optimize when something is performed, and do a cllback? without checking everytime inside the update?
could also do a coroutine and cancel it when not holding and things like that but update is fine
No that is not the point of the new input system
The new input system provides flexibility
Event based handling is just one option it offers
I thought it was something like an optimized way to handle performed actions, instead of checking them every frame in the update
I guess I'll do what's easier to understand for me now, like maybe a variable saving that state
It is not a performance optimization
I'd argue that it's not some extreme optimized solution from the older input system. It's cleaner and allows for quick key rebinds that's for sure
Not sure what is a coroutine, I'll have a look on that (I've just started learning and there is so many things I don't know)
The events are still being checked every frame
I'd suggest just poll the input if you're not too aware of events if you want to get started on something
using the legacy input system
I understand, I thought there was some kind of optimization underneath lol but yeah it surely make the handling more cleaner
Performance was never the concern
It would probably be better at this point, every tutorial I find, it's using the old system and many times I just don't know how to translate it in the new system
btw I'm looking inside the InputAction class, and I'm finding some events which would maybe help on that
btw you can still use events with generated class/c# events for held button, you just need to set bool inside started/canceled and just set Action Type to Value Any
Thank you! I'll have a look on that too!
np. ofc you can use polling too, and the method you saw
private void Update(){
myHeldbool = myCustomInputs.Player.Fire.IsInProgress();
}```
how can i set a particles velocity to the emitters when the particle is spawned?
possibly without a script?
oh
i found
ty
Hey! It's my first time using the whole get; set; thing and I'm a bit lost on what's the proper syntax for what I'm trying to do. I've read the debug errors and I think I get the gist but I'm still lost.
you've redeclared the maxHP variable as a local variable inside of the setter but also it's after you attempt to use it
remove that extra declaration, make sure to return maxHP in your getter too
oh and your property (which is what you referred to as "the whole get; set; thing") is private
guys can someone help please
var writeTask = File.WriteAllBytesAsync(Global.TempZipPath, request.downloadHandler.data);
yield return new WaitUntil(() => writeTask.IsCompleted);
This thing results file being created like normal in Editor
But in builds it creates file with 0 bytes
i did log how many bytes i download, its not 0
but also, what's the logic you're trying to achieve there? you aren't using value, so you aren't actually setting the property
oh yeah that too, completely slipped my mind lmao
oh— so value is how you return the value of the property? Instead of currentHP = maxHP should I have value = maxHP?
your assignment is backwards too, but yes
oh. I actually don't want to redeclare maxHP! I want it to pull the pre existing global maxHP variable
or wait no this whole setup is confusing because you don't seem to understand how properties work
I don't :P It's my first time using them. I've read the documentation but I'm still lost
you need to declare a field to store the value of your currentHP because the property itself doesn't hold the value, the backing field does
What I'm trying to achieve is simple: when I write into currentHP, make sure it never exceeds maxHP
OH
I feel like a function is easier to start with instead of a property
IS THAT SO?
yes, properties are basically just methods that look like variables
if that's the case I'm cooked— I've been {get; set;} damn near every variable in the entire project
thats just syntatic sugar for 2 methods(getter and setter) with backing field
i tried doing this simple lightswitch code but for some reason it doesnt work, the icon appears so it its conisdering itself inside the trigger but when i press E nothing happens
thats an exception. {get; set;} makes the backing field for you internally by magic
that is fine because that creates an implicit backing field. if you put any validation code in the getter or setter you need to explicitly declare the backing field
This is what the average class in my code is looking like
those are all auto properties which means the compiler creates the backing field for you
probably not a good idea to Input check 1frame event inside Physics update loop
make a bool that you check for input in update then use that bool in the trigger method
interactPressed = Input.GetKeyDown(etc.
OnTriggerStay(){
...
if(interactPressed)
//dosomething```
well those properties set and get have empty bodies, why not to use just public fields then
most of them are likely from the interface which requires using properties because interfaces cannot have fields
ohhhh ok. So, if I don't write any code for the get; set; properties, I don't need to worry about this. sounds doable.
And if I do write code for the get; set;, what's the "write" way of doing a backing field? When referring to this variable in my code, do I call currentHP or backingCurrentHP or something?
but also it's typically better to use a property over a public field anyway to ensure you can change the way the property behaves if it becomes necessary without affecting the places it is accessed at
You make a private variable somewhere, then you read that variable in get and set it to value in set
Mhm, that's partially it. For the others, it's simply because I've been told it's good practice. Some of them like the maxHP I want to write code for. And others I want public get and private set. So I thought it would be easier to just propertify everything.
I would do:
public int HP
{
get => _hp;
set => _hp = Math.Min(value, maxHP);
}
private int _hp;
private int maxHP;
Something else that's been puzzling me is this compiling error in particular.
that is for sure the way to go about it, you just need to understand how properties actually work.
I don't normally do this because i hate spoon feeding, but this will explain how you should structure your property (also i will be using proper name conventions rather than what you are using):
[SerializeField] private int _maxHP; // this is obviously the field you are using to validate the property's max value
private int _currentHP; // this is the explicit backing field, in other words this field is what is actually holding the value that is returned by the getter for the following property
public int CurrentHP // property declaration
{
get => _currentHP; // you have to return the value of the backing field in the getter to provide the correct value when getting the property
set => _currentHP = Mathf.Clamp(value, 0, _maxHP); // this assigns to the backing field using the `value` keyword which is what contains the value being assigned to the property, i've used Clamp here to make this shorter since you probably don't want it below 0 anyway
}
unity does not use the latest version of c# so you cannot use the c# 14 field keyword in properties
Ah thank you so much! Sorry for requiring things to be explained super in depth, I think I may have bitten a little more than I can chew with this project and the official documentation is still a bit cryptic to me 😭
once that version of the language becomes available though, we won't need our full properties to have an explicit backing field anymore which will be convenient
oh i should also mention i've used expression body syntax for the getter and setter since each one is only a single expression. if that's not something you are familiar with you should look that up too
Ok bet 🫡
[field: SerializeField]
public int FooBar {get; private set;}
something else fun you can do with properties
yeah that's nice for modifying the propery's value in the inspector
Ok yeah this part I grasp!! I like this one
yea its a way to add an attribute to the backing field so we don't have to do it the manual way.
does mean however the actual serialized var name is blahk__BackingField
So, my only question right now is: Now that I have a backing field and a property with Get; Set;, how do I interact with this in other parts of my code? Let's say I need a function that displays my HP. Which one do I call, the backing or the property?
ideally the property that should be Get public only
one of the main benefit of props is to give write access to its own script while keeping outside scripts on a Read only requirement
if you have extra logic to run in the Property then always grab/set the prop if its Get or Set
normally your backing field is only there to set values within its own class
int maxHP;
int tempMaxHP;
bool hasTempMaxHP;
int tempHP;
int _currentHP;
int currentHP
{
get
{
return _currentHP;
}
set
{
if (tempMaxHP > 0)
{
if (value > maxHP + tempMaxHP)
{
_currentHP = maxHP + tempMaxHP;
}
}
else
if (value > maxHP)
{
_currentHP = maxHP;
}
}
}```Is this better implementation? :> Did I succeed
clamp() will make it a lot easier to maintain
also can benefit from props using correct casing
i presume you want Mathf.Clamp(value, 0, hasTempMaxHP ? tempMaxHP : maxHP)
are all the variables ment to b private?
i like camelCase 😔
camelCase the goat
oh yeah, clamps!!
keep camel for private vars, props and methods should ideally be Pascal
camelcase is great.. but public could be Pascal
i hate c# naming conventions lol
java's naming conventions much better
private int currentHP;
public int CurrentHP
{
get => currentHP;```
I usually use pascal for methods and classes. I assumed vars in general were camelcase
looks better imo
i also use camelCase for vars
but i dont tend to use them as often
haha people do whatever they want
the whole point of convention is to be able to tell right away at glance what the thing is, no one is forcing you to
private myVar 😀
private m_myShitVar 🤮
the unityWay ™️
m_ can go die in a fire
its 2025 we dont need to prefix var names with dumb info like unreal engine
if u still use m_ ur trying to be hipster
b_myBool 🙃 🔫
I think its people in the backend are working on C++ and can give a shit about C# conventions lol
it seems to change on a whim what conventions they use
cinemachine had a mix of Props and Public fields, it was a weird flex lol but that was a bought asset so it doesn't count ig
hey guys, im having an issue where a public feild assigned in the inspector becomes a null value when i run the program, spent the last hour looking between the two scripts and their isnt something that should be messing with it like this, is there some setting or something I fucked up?
something in the script is setting to null
One "typical" naming convention I know is right but I just don't like and opt not to use is saying something like n instead of number for local methods
Looks bad to the eye idk 😔
How did I like replace an asset from another without losing the references?
copy the fields
Like in, I just updated an image and want to replace it
and paste em in
What???
I don't wanna copy a component, I want to update an asset with a newer version of it
oh..
that doesn't sound like a code question.
and if you have an image file that you want to update, just . . . save over the existing one. that's literally it
Where do I ask that then?
if the name of hte image is still the same.. updating it should keep the reference..
If I drag the new one in assets, it makes a new one with an extra counter next to it
replace it in FileExplorer
i didn't say drag the new one into unity, i said save it over the existing one. either by replacing it in your file explorer or literally using Save As in whatever image editor you are using
it needs to literally replace the existing file. or you can just rename the old one's meta file to be the same as the new one 🤷♂️
Saving over the older one does not actually update in Unity, I think it creates a copy when dragging it??
it does
the only reason you might not see it update immediately in unity is if you turned off the automatic asset refresh. but that would be your fault, and not because it isn't actually updating.
then saving over the existing file will JustWork™️
if this worked the way you assume it did, then every time you saved a script it would create a new copy of the script. that would be absolute fucking chaos. it does not work like that. if you save a file it will update that file.
I thought id have file scoped namespace in Unity 6. I remember creating a new project in beta and had that.
simple, on and off sistem but for some reason it doesnt work
the icon appears so it is checking that i enter the collider
which GameObject is this attached to?
a point light
oh im sorry my mistake
its attatched to a lamp
the object its trying to turn off is a point light
Adding Debug.Log will help you understand what is going wrong here
Also you didn't really explain which part of this isn't working
What ar you expecting to happen that isn't happening?
the gameobject doesnt turn off/on
that would be incorrect. that is a .net 6/c# 10 feature which unity does not support
Which one
the lamp
Make sure you have the correct object referenced
the icon appears and dissapears
and that you're looking at the correct inspector
Also make sure the object that this script is attached to is active at all times, and that the script is active at all times
Can you show the inspector for the object with this script on it
But I think you can set the syntax to a higher C# version no?
I have a project in NetStandard and using file scoped namespace just fine. Just need to add this. <LangVersion>10.0</LangVersion> even if it also has <TargetFramework>netstandard2.1</TargetFramework>.
!code
Unity 7
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
changing the language version only gets you syntax sugar, anything that requires the higher .net version will not be available
gotta wait for the CoreCLR switch
I'm just saying, i can still use file scoped namespace as long as I set the lang version.
A tool for sharing your source code with the world!
and yet no version of unity ever had c# 10 as the default language it supports because unity only supports c# 9 (and not even fully since it doesn't have .net 5). i was responding to your initial statement of "I thought id have file scoped namespace in Unity 6"
the shuriken follows the player instead of going straight
its because its doing exactly what you coded it to do
you assign its x position to the player's position immediately before moving it forward
so how do i make it go straight after it spawns in front of the player?
obviously don't assign it to the player's position every frame
also if it has a rigidbody on it why are you moving it via the transform?
how should i move it?
using the rigidbody
ill take a look
i just woke up and it works again, i didnt change anything shit just starts working after i went to sleep
does someone knows how to get rid of this white border thingy
im pretty sure its from the canvas
or
sth
idk how to get rid of it safely
tho
thats just the gizmos
also not a code question
collider = GetComponent<MeshCollider>().sharedMesh;
//generate mesh that works 100%
collider = mesh;```
The collider shows nothing in the mesh field in the editor.
why is this?
are you actually assigning it back to the mesh collider? or are you expecting the collider variable to somehow assign the mesh to the sharedMesh property of the meshcollider?
I am assuming that the shared mesh is supposed to be a reference to the mesh.
sure, but are you actually assigning to that property anywhere
collider = mesh;
that is assigning to your collider variable
collider = GetComponent<MeshCollider>().sharedMesh;
here's a thought experiment for you:
string one = "one";
string two = one;
two = "two";
what does the variable one contain after this code executes
Hello, I am trying to figure out my character movement right now, I am using rigidbody addforce to move. My issue is, when I run onto a slope, even a minor incline, the movement slows way down, any suggestions on a fix?
well, first of all you should send the !code if you want us to help with it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
and secondly. you should have the character move along the surface normal and then divide the movement force by some dampener as the slope increases
Hey y'all. Something weird is happening with my code. It's accessing my code and turning a variable into the thing it should, but then is immediately returning it back to 0. I want it to be 4, and it does it for only one frame. Any ideas of why? I have no idea what could be causing it.
The code: https://paste.ofcode.org/vumCBRZUfGp8pHAA8hkaWf
The reseting works, only turning it to 4 does not, as seen above. (please @ me if you respond! Thanks)
camelCase is overrated we should switch to raNdoMCasE
What do these two methods do?
PlayerDeckManager.ResetPlayerHandVoid();DealerDeckManager.ResetDealerHand();
A little bit of a lot, let me get it for you
those are the only other methods that are called. do either of them access currentBet?
also SerializeField is used to store (save) private fields and display them from the inspector. public fields are serialized by default . . .
They do not, and if they would, they would restart it everytime the function is called (it works for when I reset hands)
I'm getting the scripts for you just in case...
The one with PlayerDeckManager.ResetPlayerHandVoid(): https://paste.ofcode.org/qSQgZsk6XjWTwCHjxrsyGU
The one with DealerDeckManager.ResetDealerHand():
https://paste.ofcode.org/w2wiBBK7AUBxjkfYKXnwHM
Also apologizes if I seem rude, I dont mean to be! Currently freaking out as this just broke whenever it's due for a school competition tomorrow.
You have to look at what accesses currentBet because it's only changed in ResetGame (as far as we know). Something else is setting its value . . .
Currently it's only saying (in the code) that its referenced by the BetManager code (the first one I showed you. Checking everything else just in case
I see that PlayerWinsBet and PlayerLosesBet set its value. Place a log at the top of both of those methods to see if either is called after it's set to 4 . . .
// In PlayerWinsBet method.
Debug.Log($"<color=orange>PlayerWinsBet</color> is called.");
// In PlayerLosesBet method.
Debug.Log($"<color=orange>PlayerLosesBet</color> is called.");
is there any way to make the jump action starting on line 43 more fluid? Right now, when I hit the jump button, I pretty much just teleport up to the jump height instead of travelling through the air
can someone please help me I am getting so pissed off. Why is my child controlling my parent objects transformation?
when I move the childs position it moves its parents position with it
Impulse is the correct force to apply when jumping. I will say, you should not be multiplying your velocity by deltaTime . . .
oh right, fixedDeltaTime, right? Also, the impulse force is still just "releporting" my character up, even though it's not that high and I changed the fixedtime...
multiplying deltaTime into your velocity is incorrect
neither deltaTime nor fixedDeltaTime should be used
also the reason your jump feels like a teleport is because of line 40
you are overwriting your velocity completely every frame
so the force only gets a chance to matter for one physics frame
gotcha, thanks will try to fix this
After it is called (Set to 4), its not. Ugh! So confusing sadly. Thinking what I may do is make a new method and call on that with the button (a button calls for the resetgame()) which sets the bet to 4. Does that sound smart, or should I do something different?
Also hey PraetorBlue!
I have a gun object (position) another object (pivot point) and I made one gun using this set up and the pivot is on stock of gun and position is in center of gun and it works. tried adding another gun and when I move child for example the gun inside the pivot point the pivot point moves with the gun and same for moving the pivot it moves the position (parent)
top works
Does anyone know a good tutorial for FPS movement? I followed Brackeys FPS and got liked it, but noticed it had issues like falling incredibly fast if something didn't have a certain layer, and if you held A & D to move you would go 2X the regular speed.
Whats your code for this?
My enemy isn't moving to a random point so I decided to draw the ray to check the point but I cant see the ray in the editor
gizmos are on
How are you drawing the ray? Also, you can log the position of the random point to see where it's located in the scene . . .
float newX = this.transform.position.x + Random.Range(-5, 5);
float newZ = this.transform.position.z + Random.Range(-5, 5);
float newY = Terrain.activeTerrain.SampleHeight(new Vector3(newX, 0, newZ));
Vector3 dest = new Vector3(newX, newY, newZ);
Debug.DrawRay(this.transform.position,dest);
agent.SetDestination(dest);
this the code
The second parameter is a direction, not a position. It's also used for the length of the ray as well . . .
Hey RandomUnityInvader(), figured out the problem and wanted to say thanks for the help. Turns out the button was calling on the script on the asset folder, not in the game 😅 Also, thank you so much for the past help that youve done!
Whoa, glad you found that out . . .
Debug.DrawRay(this.transform.position, dest - this.transform.position, Color.red, 5f);
something like this will work then?
Sure, give it a try. You don't need this; it's already implied. If you multiply the direction by a value), that will be the length of the ray . . .
Thanks for the help , it worked
Nice!
Its happened a ton lol! Have a good day man, respect ya a ton
Yes, you should normalize the result, but only if you want to use a distance. This will still display the direction correctly . . .
I set up a nested rigidbody 2D. The uppermost is dynamic, the rest are kinematic.
I noticed that the dynamic rigidbody doesn't utilise the colliders that attached to the child rigidbody.
Is that normal behaviour?
This isn't an issue, since i'm planning on using them for animation and have a separate collider for interacting with walls.
yes, they are considered separate rigidbodies, colliders are only part of the closest ancestor rigidbody's compound collider
For some reason transform.position = Vector3.zero; prevents transform.SetParent(null);
Does anyone know what is going on here, and how to fix it?
how do you assume that ?
testing. i used to have a problem with double triggering a function, that why i added the transform.position
what do you mean it prevents transform.SetParent, that makes no sense
i just fixed the issue by using setactive(false) instead but its still weird
literally it doesnt happen, the object remains on its parent
how did you verify the function is running
how have you actually confirmed any of this
everything else in that function runs fine
show the full code
by testing yeah, if i remove the transform.position line setparent(null) works again
and explain how you have actually confirmed this. because what you have said makes no sense
the relevant code:
public override void GiveFood(Food_Base _item)
{
// Eat
_item.transform.position = Vector3.zero;
_item.transform.SetParent(null);
_item.gameObject.SetActive(false);
// Check if correct order
manager.CheckOrder(_item.order);
}
show the full code. because i have a feeling that something else is affecting it since setting the object inactive apparently fixes it
something like this:
test 1 (with this code): _item is not removed from its parent, everything before and after works fine
test 2 (remove transform.position line): _item is removed successfully, but triggers CheckOrder twice for some reason
Food(Clone) is _item
Making it inactive doesnt solve this problem, it solves the double trigger problem and then i can just delete transform.position since that was its only reason to be here.
apparently you don't know what the word "full" means, but i'm not going to bother asking again so good luck getting this figured out
Hey quick question. Trying to figure out how to skip items in a queue:
I have a queue of 6 items, being the sentences in the boxes photo (following a brackey's tutorial). Currently, I have these items in a queue, however, I want to be able to skip to certain lines when a variable is called. If I remove items from the queue, will it destroy this string list? Or how would you go about skipping lines? Here is how I am storing the string[]:
public void StartDialogue(Dialogue dialogue)
{
Debug.Log("Starting Dialogue with " + dialogue.OpponentName);
nameText.text = dialogue.OpponentName;
SentenceQueue.Clear();
foreach (string sentences in dialogue.sentences)
{
SentenceQueue.Enqueue(sentences);
}
DisplayNextSentence();
}
``` Any help is much appreciated. I apologize, Queues are not my thing 😅
a queue is supposed to be first in first out, is there a specific reason you're using a queue and not like a list if you want to be able to just skip elements?
Actually thats fair. More this is what it was already coded on, so Ill probably just have to make a new method real quick. Didn't realize it was first in first out 😭 . Mainly its because of this:
if (SentenceQueue.Count == 0 )
{
LevelContinueButton.SetActive(true);
EndDialogue();
return;
}
Do you think I could make a new queue with specific items from the list? Is that unoptimized?
FIFO is the entire point of using a queue
Just use List ™️
Do you think I could make a new queue with specific items from the list? Is that unoptimized?
what are you actually trying to achieve here?
https://xyproblem.info
Here: I want the player to click buttons to go into different dialogue options. It runs through the dialogue, then when player presses continue it goes onto next piece if it has dialogue, or returns to dialogue options if not. I have a list with the sentences already, so i need to just go into that list each time for each specific one, right? Sorry, want to make sure Im getting y'alls idea right
if my player and monsters are moving around in fixedupdate with physics
if I program a player attack, should it also be in fixedupdate? or is it ok to be in update?
yeah you could use a list for that.
you could also consider looking into assets like yarn to implement dialogue
doing it in update should be fine, if you're using physics queries (like raycasts, overlapbox, etc) then it just queries the current state of the physics engine
it is a multiplayer game, so not sure how that might mess with things
Now in simplest form your dialogue options can have index of dialogue it would jump to, but it would be hard to manage
You'd be better off with proper dialogue tree
Like this?
https://paste.ofcode.org/j8YpTGSGRrAksrYrXEZeqS
Also, Ive never heard of a dialogue tree. Is there any good resources that you know of for researching that?
(Also, yeah its simple. This is my first coding project for a school competition 😅 ) Thank y'all for the help though, it means so much to me.
If you are doing typical server-client model multiplayer, server has authority and should do all the calculation. Client can predict actions but it shouldn't affect actual result.
Weird thing that is happening now. Currently it keeps saying that my index is out of bounds? I was thinking that the thing would be fine, but its bugging out on me. Here's the code:
https://paste.ofcode.org/m6bH6jNdyN34Qn85tSrKmd
And where it is specifically breaking:
if (WhoareYou == true)
{
(Here) sentencesaying = Dialogue.sentences[6];
StartCoroutine(TypeSentence(sentencesaying));
ContinueButton.onClick.AddListener(EndDialoguePostWin);
WhoareYou = false;
}
``` I don't know, still pretty confused on why it's breaking.
remember that arrays and lists start at 0 so their Count will always be one higher than the last index
Right- That 6 that you see is what the count is. Should I say 5 instead?
Ohhhh
Consider using a dictionary and listing the dialogue items by a key if you want an easier time getting dialogues
Right now you have an index with no clear explanation what it is, which can be confusion
Alternative an enum is also nice because you can give a name behind the index
Hey, I am working on a game with a system that requires inputs from the player in order to do an attack (Left arrow, right arrow, up arrow, down arrow like Friday Night Funkin or Dance Dance Revolution) and I am working implementing attack animations to each arrow input. Any idea on how I would set the animation to only play of the last input pressed?
I am using animator in Unity for the animations
Yeah, I really need to. Still really learning how to do dialogue and rushing for a submission tomorrow, but real quick, what do you mean by dictionary? I've never heard of it
The idea of a dictionary is that you can specify a unique key with a value
So you can define a dictionary with 2 generic types that indicate the type of the key, and the type of (in this case) the dialogue
Huh. I need to look into that, that actually seems really useful!
Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>();
// You can also fill it with lines from initialization
Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>()
{
["Dialogue1"] = "Hello, World!",
}
// Or add it later.
dialogues.Add("Dialogue1", "Hello, World!");
dialogues["Dialogue1"] = "Hello, World!";
Syntax might be a bit off here
Then you can just get it with dialogues["Dialogue1"]
There are additional checks to ensure a key exist:
if (dialogue.TryGetKey("Dialogue1", out var dialogue))
{
// The dialogue exists
}
So you see it's easy. It's also very fast
Just make sure the keys are unique obviously
If you’re pressed for time it might not be the best option right now , but in a past jam I did I liked the system we used, which was to have a dialogue queue defined in a ScriptableObject, with a UnityEvent field in each dialogue that would invoke when that line was finished. So you could then trigger different dialogue like a choice dialogue, or enable/disable objects, etc.
Oooo ok. I still need to study it a little more (I promise you, im beginner beginner. This is my first coding game), but I really want to try it!
Most likely 😅 Quick question that I am confused about is the out var? On the additional check message (one i replied to). Also, is dictionary like a type?
Dictionary is a generic type. You define the types of the key and value in the <,> part of the declaration
So like <string, string> means that you lookup a string by using a key as a string
Just a real dictionary. You need some block of text (the definition of the word), which you look up by the word itself
“Try” functions usually return a bool and an out parameter. What this means is that if what was tried was successful then the out parameter will be valid, otherwise if it’s false then the out parameter won’t be valid
It saves you from having to validate it more specifically
There are methods that start with Try. These are often, if not always, using what called the "Try Parse" pattern. The idea is that you attempt the action, and instead of returning the type as a result it returns a boolean indicating success. Any additionally returned information (such as the dialogue in this case) is returns in what's called "out parameters". These are explicitly keyworded with "out" to indicate they are set inside the method and will have a value when the method ends.
If the try method returns true, it can be assumed all parameters with "out" are set
This is the code behind the Dictionary. Note it explicitly has out defined, and therefore will set this variable before it ends.
Otherwise, it returns default(TValue), which is often just null
Also, is dictionary like a type?
Yes, almost everything in C# is. Maybe you mean the<string, DialogueType>part?
Dude this is actually so cool! Trying it out right now.
The Try pattern can be found in many things. For example, int.TryParse attempts to parse its parameter (which is mostly a string) into an integer, and returns a boolean type indicating if it works
Theres also int.Parse which instead tries to parse, or throws an exception if it failed
Nope, just didn't know where it would go honestly. So what could my dialogue type be? I have a dialogue script:
using UnityEngine;
[System.Serializable]
public class Dialogue
{
public string OpponentName;
[TextArea(3, 10)]
public string[] sentences;
}
But thats only for the queue method. Would it be something else?
So you see there's generally always an alternative that's not as graceful
Only problem is you can't serialize dictionaries with unity :D
Yeah, Unity doesn't support this natively. There are packages online that add support though
Not for the actual type, I believe. They add a new type similar to the Dictionary, but makes it serializable
Uh guys how do you make the character move? , im a beginner and dont rlly understand anything
There are resources online that will help you !learn Unity and how to implement features. You can also check the pinned messages in this channel for more resources.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Generally you'd use the character controller or a rigidbody for these things.
Quick thing if youre still here. Here's my code for trying it out:
Dictionary<string, string> dialogues;
dialogues["WhoareYou"] = "The holder of certain parts of this universe, just as you.";
public void DisplayNextSentencePostWin()
{
if (WhoareYou == true)
{
sentencesaying = dialogues["WhoareYou"];
StartCoroutine(TypeSentence(sentencesaying));
ContinueButton.onClick.AddListener(EndDialoguePostWin);
WhoareYou = false;
}
But now its giving me a null exception. Do I have to connect it to another gameobject?
What is line 204?
I might we wrong in saying the [""] = ""; type syntax adds the key if it doesn't exist. Use the Add method in that case
I thought it would
sentencesaying = dialogues["WhoareYou"];
``` This one, which usually calls the throw off
Add method? How should I do that?
See code above
Do anybody know if you can acheive the effect of a 3D model as a Canvas sprite in unity or did the person that made this game import png sprites for the inventory UIs?
Not sure why it would throw this exception. I would expect a KeyNotFoundException
Eh, wouldn't be surprised if it was my code sadly. Checking out to see if the Add works rq...
By the way, note that a dictionary is case sensitive. If you check for the key "WhoAREyou" it would throw a exception.
This is something that can be disabled, if you don't want this
Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>(StringComparer.OrdinalIgnoreCase);
Note the added StringComparer class
Weirdly enough, its giving me the same thing: NullReferenceException: Object reference not set to an instance of an object
I just don't know what its trying to access though
I would suggest you check if the key exists beforehand, then. If it still happens after it's not related to the Dictionary
Its probably the key - Need to figure out how to add that
Sprites would certainly be the most effective way. If the images do not move/animate there is no need to render them every frame
I have this extremely simple setup.
A capsule that can move in 4 direction with a sword sprite as child that swings.
What's the best way to get the sword facing the other 3 directions when moving/facing those?
Also why does changing my player rotation to 180 rotate my tilemap?
I can't imagine being able to rotate that 90 degrees if it's not a top-down 2D game
it's a top down 2d
If it's 2D you can just rotate with eulers usually. Don't have to worry about gimble or anything like that
you can actually use Quaternion AngleAxis too if you wanted if you specify z as up
thank you very much
cool that works 🙂 didn't realize you could use the z axis in 2d
if (moveInput.x > 0) swordTransform.transform.eulerAngles = new Vector3(0, 0, 0); // Right
Isn't this a bit overkill?
Can't I just directly set the transform.z value?
I dont think you can set independent values. Gotta make a new vector each time
I need to create a money script so player van buy weapon off wall
go type that in youtube: "unity money script"
Mornin all, been a while since I've been around here.
I'm having a bit of a struggle with a little simple 3rd person turret game idea. Idea is that the player controls a turret and has to shoot at paratroopers dropping to the floor 'downrange'. I'm using a raycast direction to control the rotation of the turret 'parts' but I'm struggling to get what I want from the vertical rotation.
I'd like for the turret's x rotation to be 0 if the mouse pointer goes below the halfway point of the screen but I can't seem to get my head around the maths involved.
This is the code I'm currently running
using UnityEngine;
public class TurretController : MonoBehaviour
{
[SerializeField] Transform turretBase;
[SerializeField] Transform turretPivot;
[SerializeField] Camera mainCamera;
[SerializeField] float rotationSpeed;
// Update is called once per frame
void Update()
{
Debug.Log(Input.mousePosition);
//Debug.Log(Screen.width);
Vector2 mousePositionOnScreen;
mousePositionOnScreen = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Ray rayToWorld = mainCamera.ScreenPointToRay(mousePositionOnScreen);
var aimAt = rayToWorld.direction;
Quaternion newTurretBaseRotation = Quaternion.LookRotation(aimAt - turretBase.localPosition);
newTurretBaseRotation.x = 0f;
newTurretBaseRotation.z = 0f;
Quaternion newTurretPivotRotation = Quaternion.LookRotation(aimAt - turretPivot.localPosition);
newTurretPivotRotation.y = newTurretPivotRotation.y/2;
newTurretPivotRotation.y = 0f;
newTurretPivotRotation.z = 0f;
turretBase.localRotation = Quaternion.Slerp(turretBase.localRotation, newTurretBaseRotation, Time.deltaTime * rotationSpeed);
turretPivot.localRotation = Quaternion.Slerp(turretPivot.localRotation, newTurretPivotRotation, Time.deltaTime * rotationSpeed);
}
}
Screen shot for reference. The white line is the screen.y halfway point.
Hello guys! Is that the right approach to delay the shooting? With awaiting Task.Delay? Or is there a better approach?
private async void FireSingle()
{
Debug.Log("FireSingle");
isShooting = true;
Shoot();
await Task.Delay((shootingDelayMilliseconds);
}
private async void FireBurst()
{
Debug.Log("FireBurst");
isShooting = true;
if (burstBulletLeft <= 0)
{
isShooting = false;
return;
}
Shoot();
if (burstBulletLeft < bulletsPerBurst)
{
await Task.Delay(shootingDelayMilliseconds );
}
burstBulletLeft--;
FireBurst();
}
Muck very cool game, anyway, to answer your question: You can use a camera as a viewport, take a picture using a render texture, and then load that based on the name of the object, it's probably best to not do this at runtime, unless required, as you can just match a texture2d to an item name or something for said pictures, but, reading the pixels of a render texture, then writing that to a file, saving it as a png, is how that could work
Just as a quick visual follow up cause I'm not sure I explained very well.
I don't think there's a "best approach" or even a better, but, some alternatives to look into if you don't like how you are doing it:
- Use invoke with a time, it will delay the call until the delay is over,
- A coroutine using
yield return new WaitForSeconds(x);
I'd say your way is perfectly fine, there are alternatives, as with everything, you can look into them if you prefer them over your way
Invoke(Method, Seconds); I believe for invoke
Thank you! It's more like I know C# because I work as a web developer in .NET environment, but completely new in Unity.. Sometimes I tend to use stuffs which I already know in C#, but there may be better approaches or more used pattern for these situations programming with Unity!
I tried the Invoke method but I was't able to make it work, because I made the methods recursive and the Invoke is not really waiting the end to fire again, so I might refactor a bit to use that.. I'll have a look to Coroutine which I have never used!
Alright, coroutines are good for delaying actions, creating things that need to do a lot without causing massive overhead due to doing it all at once (as you can use yield return null in a coroutine to wait for the next frame, rather than, a method which will execute everything in one frame), you'll definitely find them to be of use
Async is also usable. You can use the third party lib UniTask or Unitys own task replacement Awaitable in 2023+. Do not use Task. (I recommend UniTask)
What's a good way to keep track of how many monsters are in my scene so I can spawn more if some have died?
I'm thinking to use a reference list on my spawn script and just count the number of entries every few seconds?
If the referenced object is destroyed it's removed from the list as well right?
Or I could throw an event every time a monster dies to adjust a count somewhere
So I'd just have a singleton like MonsterCounter that keeps track of all the monsters?
Guess I can adjust it to include which scene the monsters are on
GameManager works fine too if you want to keep it minimal
I say EnemyManager if you want to do something like object pool
You know a good way to cheese this? Just add some invisible collider planes so you can't raycast below the turret and similar idea for the background if I'm understanding the question correctly
Yeah, that's how I usually do with things. The problem is that when it moves to a 'new' collider, there's a horrible 'snapping' if they're at various depths.
make the background plane very close to the turret
so the depth is smooth
probably better ways to handle it but I think that can work
Yeah, but then you lose accuracy when shooting far off distance. lol. (I know, sorry, really not trying to be a pain. lol.). I'm going to try using a sphere collider somewhere 'middle' distance (I want the paratroopers to drop at different depths) that I think will work.
The proper way would be to use Time.time and manage the delay with timestamps. See the documentation from the URL for an example.
The convenient thing about this is also that you're not hard tied to an interval. If for some reason you want some sort of cooldown, you could just decrement the value of _nextTick (or whatever you end up calling it) instead of extra steps to get it working
And also, if you had to tie a visual indication of the time left, you can just get the difference _nextTick - Time.time and use the result in some progress bar for example
And lastly, if it matters to you, this is very multiplayer friendly since you just need to inform users of the next timestamp in most cases.
Your approach also works. Alternatively a Coroutine also fits in here. There are no wrong paths with it really, but I personally had the best experience with Time.time
public class Example : MonoBehaviour
{
private float? _nextBurstFireTick = null;
private float _burstFireInterval = 0.1f;
private bool IsBurstFiring => _nextBurstFireTick != null;
void Update()
{
// Fire the next shot
if (IsBurstFiring && Time.time > _nextBurstFireTick)
{
Fire();
_nextBurstFireTick = Time.time + _burstFireInterval;
// Additionally you'd increment some counter here to ensure we stop firing at some point.
if (HasShotThreeTimes())
{
_nextBurstFireTick = null;
}
return;
}
// Start burst firing
if (PressedFire())
{
Fire();
_nextBurstFireTick = Time.time + _burstFireInterval;
}
}
}
Semi pseudo code, gets you an idea of how Time.time can very easily be included with a system so you can separate the burst firing logic
And yes, this is all copy pasted from a previous message
Thank you! Yes I will surely add a multiplayer later (very later on 🤣 ), I might give this Time.time a shot!
Good luck! 😎
Any simple way to detect if an object I would Instantiate would collide with another object before instantiating it?
For my monster spawner, so I don't spawn monsters (which collide with eachother) inside another monsters collider
Or should I use a simple workaround like force them to move away from the spawn point?
I'm not sure how efficient it is tbh, but I've always used OnCollisionStay ( or OnTriggerStay) if true, move it, if not move on to the next thing.
Ah, 30 minutes wasted on trying to figure out why Physics.OverlapSphere is not working, to then figure out I need Physics2D.OverlapCircle
how do I make it so that it loads the next scene on the build index? ignore the method name
SceneManager.GetActiveScene().buildIndex + 1
ight thanxx
int next = SceneManager.GetActiveScene().buildIndex + 1;
int max = SceneManager.sceneCount;
if(next >= max)
next = 0;//Repeats but it's really your choice on what to do instead
SceneManager.LoadScene(next);```
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
hi, im making an incremental game and im currently making the upgrades for it. how should i go on about making upgrades that do different things (i.e, one upgrade adds +1 to your click and another sends a robot out to do clicking for you)? is there a way to implement all of these possible behaviours into one central UpgradeItem script?
I would try to think in abstractions. You want to be able to change what happens when you click, so that's some kind of "ClickBehavior", but you also want there to be a robot that can do the clicking for you, so this is some kind of "Clicker" system.. Normally, the Clicker is of type CursorClicker; and a CursorClicker is controlled by the user for manual clicking. Every time the CursorClicker calls Click(), it invokes the DefaultClickBehavior (adding a 1 to the score). At some point, the user upgrades their ClickBehavior to a BetterClickBehavior- Now, when their CursorClicker calls Click(), it invokes BetterClickBehavior which adds 2 to the score.
Then the user gets an upgrade that swaps out their CursorClicker for a RobotClicker; Now it's not controlled by the cursor any more, but by a robot that goes out and calls Click() on its own, invoking the current (or default) ClickBehavior every time.
You'd probably implement this with some kind of base class that has a type of IClicker and IClickBehavior. But architecturally there's a lot of room for how you set it up and what exactly you need for your game specifically.
https://paste.ofcode.org/RaifL7TG6dhMPgFpYVrj - code
hi im trying to get my character to move in sin(x)
but for some reason i keep getting 1/x
can i get help with it ?
wdym?
you'd want a parabola that opens downward, so y = -ax^2 for some a
but you don't need to actually have a parabola
where can I ask for help with unity's editor?
thanks
a parabola is just the shape an object traces under gravity, ignoring air resistance
so just simulate gravity and you'll get a parabola
@ashen frigate
i need x^2/a and a needs to be a bigger number so it wil go up slower rn is shot up
hi, thank you for this solution! i just wanted to know, can the player still click manually and have the robot click for them at the same time with this approach?
Yes, you can do whatever you want.
The above example doesn't do any functionality, it's purely for organizing your data so that you can incorporate it into the logic and gameplay.
Right, like Osteel said, it's purely up to how you implement it. I imagine you could easily have a collection of IClicker, for instance.