#π»βcode-beginner
1 messages Β· Page 769 of 1
they could be
errors can be a lot of things
if you don't know, then ask instead of ignoring
doubt it
yeah because that's unrelated
perhaps actually check the errors
send them here if you don't understand them
no those werent the problem i fixed the layout
now i can go back to the script
i was able to fix the problem
finally
looks like auto save wasnt saving my input so i just save manualy
but have you gotten visual studio configured
im gonna do it now
its working now
thx
Hello can anyone see what's wrong with my localization code, i'm trying with Tap {count} times but it keeps showing me the value I set in the editor and ignoring this. So I keep seeing 100 instead of 4 if I remove the value from the editor it fails straight away. withError parsing format string: Could not evaluate the selector "count" at 5
Looks like it expects a dictionary as the arg
(iirc it can accept a lot of things)
mb meant to delete it :(
I think if it is keyed in the string, it needs the dictionary, but if it is indexed it needs an array? It's a tad confusing at times for sure on the specifics.
what is the 2nd screenshot here from?
it's always an array, but if you use a name it can be from a dict or (i think?) a struct using reflection
but yeah i don't think a single integer is in the options
If you did "potato: {0}" then you could just pass in the int for the arg, but with "potato: {Count}" you need either a dictionary or an object with that named field yeah. The reflection item on the left (under sources) shows the class one
but that second screenshot seems like they have variables set up separately, so im kinda confused on that
Can even do xml, what in tarnation
Hm, how can I make 2 separate game objects to communicate with each other (like Player to UI to update health)? I would normally use Signals in Godot, and Unity has Events, but not sure if people actually use Unity Events for this.
Thanks guys, I'm still a bit confused lol but I will give that dictionary example a shot as I might just need to add that second line with "Count", Count...that cant be right either π€ . I think I may need to try and spend some more time in the docs
Make one of them reference the other one.
https://unity.huh.how/references
Choose the best way to reference other variables.
Got it! Seems simple enough
Unity has Unity Events which you can hook up in the editor, or c# events which you do from runtime binding
but too lazy for that and rather just direct reference when possible
usually the idea is those objects further down the hierarchy should have events to the parents if it does need to communicate back
But if communication is one-way (downward), it's proper to just direct reference if we're talking static elements
Mhm, it should still be loosely coupled when using references
Events are typically one-way, no? I just think they save us from the nasty references when too many objects have to be triggered
Thats the point of events, to allow anything to add a listener (or not)
the invoker of the event doesnt need to know about any listener
hi. im trying to make a simple bus controller with wheels.
however, with no inputs the bus jumps out like so in image 1
code: https://pastebin.com/jdte5z5h
bus set-up - image 2
wheels - image 3 and 4
(the bus model is not mine if thats of importance)
if i've left any helpful information out, please let me know
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
(video of what the bus does)
but yeah please can i have a possible cause and possible fix for this? i'm not even sure why this is happening
I'm probably overcomplicating this to no end, but how would I check if the velocity of a rigidbody does not exceed the maximum speed in a certain direction? This is what I'm doing right now but I'm not sure if this is correct at all:
bool exceedsMaxVelocity = Vector2.Dot(playerRigidbody.linearVelocity, movementVector) / movementSpeed > 1;
playerRigidbody.linearVelocity +=
exceedsMaxVelocity ?
Vector3.zero :
movementVector * (acceleration * Time.deltaTime);```
i meant with no input. it just decides to shoot off whenever i press play
sorry, i should have specified
And in turn I want to accelerate the rigidbody in the movement direction (given by the input), up until its velocity in that direction exceeds the max speed
I hope this makes sense
I'm just trying to make a 3d rigidbody player controller that doesnt overwrite the velocity directly and doesnt add force
The only thing I find to be changing the wheel positions is the GetWorldPose method. Have u tried the code without that?
Do you have any errors in the console?
oh that works. thanks!
no. no errors
is there a reason for the whole "maximum speed in a certain direction" part? like would there ever actually be a case where you have an object being pushed sideways and still want it to move at full speed going forward
quick question about dictionaries, do i not need arrays if i'm using a dictionary?
example:
private void Start()
{
peopleAndSeats = new Dictionary<GameObject, int>();
peopleOnBus = new GameObject[64];
seatNumbersTaken = new int[64];
}
void AddNewPerson(GameObject passanger)
{
int seatNum = -1; // Default val -1
for (int i = 0; i < seatNumbersTaken.Length; i++)
{
if (seatNumbersTaken[i] == 0)
{
seatNum = i;
peopleAndSeats.Add(passanger, seatNum);
peopleOnBus[seatNum] = passanger;
}
}
}
You do not need an array, but c# has a special dictionary which includes a way to iterate over it via foreach
ahhh thank you
no guarantee on ordering
it's stored in the dictionary, if theres ever a reason you need to get all the gameObjects you could iterate over it or even grab the peopleAndSeats.Keys
tbf im not too fussed on ordering. if someone is in a seat, then it skips over it
ahh thanks!
also does the key come first?
like the gameobject is the key
so it is
you iterate by the key entry, yeah
if you want to iterate by unique values only*, you'd probably need to store those values into its own data struct
well, you iterate by kvp
oki thanks
meaning that you can come across the same value multiple times if multiple keys do point to it
i mean, the way i see it is that i want the object to preserve momentum after being pushed around and stuff
while still having a maximum speed it cannot go above without being pushed by something else
so like if the player is pushed backwards with a speed higher than their maximum, they cant accelerate backwards but can slow down forwards
how would i do that?
what you have is likely fine except the Vector2.Dot seems weird considering you're using vector3.zero later. If this is 3d then you should grab the specific values you want from the linearVelocity because otherwise I think you're comparing the xy values rather than xz which is horizontal movement.
If movement vector is always normalized then id assume this works fine. if the movement vector isn't normalized then comparing this to your movementSpeed is wrong
though still id really question if this case ever comes up in your game. Id just compare the .magnitude of the horizontal components of the linearVelocity to this movementSpeed
movementVector is just the direct value from the input system
also ohh i see yeah, it should be vector3.dot instead
you need to normalize it anyways because you're using it for adding to the velocity
well actually i dont know if its normalized already. you can double check that pretty easily by printing out the magnitude
but its already normalized no?
it is
its not 1,1 its sqrt(2),sqrt(2) when holding diagonally
so should be normalized
1/sqrt(2) or sqrt(2)/2 hopefully but yea
whatever 0.707 is i forgot π
okay this seems to actually work quite well! needed to tweak the max speed/acceleration and linear damping values but it feels great
yeah sqrt(2) is about 1.414
flow launcher is great for those quick math checks 
Tf is flow launcher?
https://www.flowlauncher.com (basically a quick app opener/quick actions)
Oh, why
I cant see my Serializedfield instances in inpector why?
public class Laserbeam
{
Vector3 pos, dir;
Gameobject laserobj;
LineRenderer laser;
List<Vector3> laserIndices = new List<Vector3>();
public LaserBeam(Vector3 pos, Vector3 dir, Material material)
{
this.laser = new LineRenderer();
this.laserobj = new Gameobject();
this.laserobj.name = "Laser beam";
this.pos = pos;
this.dir = dir;
this.laser = this.laserobj.AddComponent(typeof(LineRenderer)) as LineRenderer;
this.laser.startwidth = 0.1f;
this.laser.endwidth = 0.1f;
this.laser.startColor = Color.green;
this.laser.endColor = Color.green;
CastRay();
}
void CastRay(Vector3 pos, Vector3 dir, LineRenderer laser)
{
laserIndices.Add(pos);
}
void UpdateLaser()
{
int count = 0;
laser.PositonCount = laserIndices.Count;
foreach (Vector3 idx in laserIndices)
{
laser.Setposition(count, idx);
count++;
}
}
}
I had a feeling that there's some problem when the objects / methods did not get coloured, Where could be the issue
I was following a yt tutorial on laser beams
seems like you used "C# script" instead of "monobehaviour script" - you're missing some stuff here, specifically a using and a : MonoBehaviour
as for the coloring, see below
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
Fix any errors, compile and reload the domain
my classes are internal I think that is source of the problem @timber tide
I would think it would throw any error here then, no? Unless you mean those are classes you've not serialized
what should I do unity sample project works well mine does not serialize
i tried asmdef for classes still not showing in inspector
Is PlayerInput here extending from monobehaviour/ScriptableObject or is it a POCO?
or just give me the class signature
in sample it overrides like this I implement this to ```cs
using Player;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Editor
{
[CustomEditor(typeof(PlayerTransform))]
class PlayerTransformEditor : UnityEditor.Editor
{
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
serializedObject.Update();
SerializedProperty property = serializedObject.GetIterator();
property.NextVisible(true);
while (property.NextVisible(false))
{
var propertyField = new PropertyField(property);
root.Add(propertyField);
}
serializedObject.ApplyModifiedProperties();
return root;
}
}
}
This looks more like a custom editor script and I assume it's just not being drawn then
!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/
π 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.
Exclude the whole editor drawer and just get your classes shown in the inspector without it
it doesnt work
maybe Unity does not serialize fields of internal classes by default in the Inspector
if the internal class is being used outside of the assembly, yeah, but I would expect some errors from either the IDE or after compiling.
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
unless the IDE isn't configured here
anyway, for the sake of testing just remove the internal keyword
is there any way to remove the "is paused" bool on other scenes? alr so i have a scene called "game scene" and another called "pause scene" and when i press escape the pause screen overlaps the game scene and pauses it and that is when the "is paused" bool turns true, but the bool for the pause scene is set to false since it just loaded in so i wanted to know if theres any way to completely remove the "is paused" button for the pause scene without having to make a whole new script dedicated to it
like is there any way to set the bool to null (ik it prob doesnt) but like have an if statement that if the scene is called "pause scene" the bool gets rid of it
thank you β€οΈ
Uh...
SceneManager.GetActiveScene().name and look is this scene exist in array of scenes on whom you wanna stop the game?
Maybe you meant something else but I understood it exactly like this.
alright let me try to explain a little better. so i have this script that enables the "pause scene" as long as it isn't named "Game Scene" or else it will be disabled. so im wondering if theres any way to do the same with the bool
If this isnt the right channel I can try a different place but I am having some trouble with shaders. I made an unlit shader in URP because I was following a tutorial. I realize now that unlit means no shadows which was dumb of me I should of thought of that. I do not want to have to try and write the shader again in shader graph because I frankly dont understand shader graph right now, is there an easy way to get basic shadows and lighting to work in my existing shader? I know in SRP you could have done #pragma surface surf Standard fullforwardshadows vertex:vert, but that doesn't work for URP
like if its named "game scene" the bool will disappear and u can make it true or false
like the pause action being disabled if the current scene is named "game scene"
I know only that you can make bool actually null with this line:
bool? name = null; (for example)
But I don't see any solution for your idea. I am a little bit tired today so sorry that I gave you no answer. Maybe somebody else can help you instead of me.
that's not a bool being null, that's a Nullable<bool> allowing you to assign null
np :) i appreciate all the help i can possibly get :D
should i just make a separeta script for it? but it would seem pointless to
Damn. My head is already refusing to work.
Do so if it will prevent you from making mistakes in the future. If it's just to remove a boolean field you'll never touch otherwise, it's probably not worth it
i could send the whole script here. its not too long
You could make an abstract scene change class, and then have two children: one for normal scenes, and one for the pause scene
Only the normal one can be paused and has the bool, and the other doesn't
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour
{
[SerializeField] private InputActionReference pause;
public bool isPaused;
private void Start()
{
isPaused = false;
}
private void Update()
{
if (SceneManager.GetActiveScene().name != "Game Scene" || pause != null)
pause.action.Enable();
else
pause.action.Disable();
if (pause.action.WasPressedThisFrame())
{
PauseGame("PauseScene");
}
}
public void ChangeLevelScene(string changeScene)
{
SceneManager.LoadScene(changeScene);
Debug.Log("Changed scenes");
}
public void QuitGame()
{
Application.Quit();
}
public void PauseGame(string _pauseScreen)
{
isPaused = !isPaused;
if (isPaused && !SceneManager.GetSceneByName(_pauseScreen).isLoaded)
{
Time.timeScale = 0f;
Debug.Log("Paused");
SceneManager.LoadSceneAsync(_pauseScreen, LoadSceneMode.Additive);
}
else if (!isPaused && SceneManager.GetSceneByName(_pauseScreen).isLoaded)
{
Time.timeScale = 1f;
Debug.Log("Resumed");
SceneManager.UnloadSceneAsync(_pauseScreen);
}
}
}
this is my code
messy ik
but if someone actually reads trough it pls tell me what i can improve on and learn to make this easier
i think imma make an abstract class, seems alot easier than.. whatever i made lol
or just make a separate component to handle pausing. why should the component that handles changing scenes also handle the pause state of the game. they can be separate and the pause component can just call a method on the scene change one to change the scene
that is true
I need help in #π±οΈβinput-system
how do i fix this error
!ide π start by configuring vs code
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
alright so i make different scripts for changing scene and pausing. should i also make a separate script for interactable buttons? or should i make them in the pause script?
or wait no
the pause script is just for pausing
nvm
guys this is a little stinky, is there something else I can do that's better?
the parameters on the Action are important for a different system
I configured it but now I have new errors it doesn't say how to fix
The error states that you cannot use line 14 as you've currently have got it.
Maybe you meant to do something like... cs a = new A[4,5];
Well, considering you've not supplied any other options, all I can suggest is refactor it all
but if this is like a small project then I wouldn't bother
why refactor?
Well, you're asking if it's smelly and if you're not using any of the params there then that would be the answer. But, not that I've not* done similar before, but usually I keep it open-ended with passing a struct of data so even if I don't necessarily need it. It's still something that could potentially be useful later on in the project. Example: DeathInfo { KillSource, KillSourceLocation }
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
these two actions are actually unrelated. you need to subscribe a method or store the Action in a variable and use that variable to un/subscribe. also when writing a lambda that you don't need the parameters for you can use discards so your expression would become (_,_) => isDead = true
_ is a discard? what does that mean exactly?
It means "This function expects to give a parameter but I will literally never need to use it so I don't care what it gets assigned to"
I usually dislike having to use them, but then I remember my input class is usually full of em
don't really care for the context most of the time
yeah mine is sort of like that - it passes an EntityIdentity class (who died), and DamageInfo (source, damagetype, damagenumber) that killed it - just in this case all I care about is that it died
man the C#/Unity wizards have syntax for everything
thanks a lot guys
learned something new as always π
just make sure you also implement the first part of my message as well otherwise you are still not actually unsubscribing π
Hey, I'm following a udemy tutorial on C# for Unity. I'm on a part for Input Events and what I'm trying to do is make it so when I hover my mouse over a cube game object it shows a debug saying "Over".
private void OnMouseOver()
{
Debug.Log("Over");
}
It doesn't work for whatever reason
when i hover my mouse over the cube.
check if you put script on object if object have collider
Yeah it's in there.
The name of the script is InputEvents
Did you run Play button to check if it is working in play mode? It should works.
OnMouseOver is part of the old input manager. If you're using the Input System, you'll need to use raycasts to determine what the mouse is over

I don't even know what a raycast is.
Well thanks for the info
It autocompletes and red highlighs but still not showing errors
If it's not showing your errors then it's not configured
what are you talking about I see red highlights when I purposely add erorrs to check so that means it's working
Okay, so it is underlining your errors
yes but there are no red highlights but still error in console
If it's the same errors you showed before, and they're not highlighted, then you have not configured your IDE. Follow the instructions.
forget I looked up alternatives to VS it's worthless
You aren't even using VS
whatever I was using it was worthless no one could even help me. I downloaded cursor AI and it fixed it
No one is allowed to help you until you configure your IDE. It's in the rules.
I told you countless times I configured it, i updated and nothing, cursor fixed the error in seconds
You didn't or your errors would have been underlined
try IPointerEnter/exit
does this really unregister? i thought this is new lambda for each register and unregister
someone else said a similar thing
I ended up replacing the parameters with discards, which fixes it... I think?
idk but i believe it still a lambda you just discard the variable
you want a method or reference to it
that does not fix the fact you aren't unsubscribing
ah ok so I do need to pass a method to it
you need to save is as a variable or make a whole new method
mb I thought that was a separate thing
Like that, or is it still not counted as the same thing?
that's exactly the same as before
I think you do need to specify the params on the methods right
if you want to use a method then your method needs to accept the parameters the delegate passes and subscribe directly with the method, not a lambda
I'm confused - so what was the discard for?
for if you wanted to continue using the lambda
and you'd need to store the lambda in a variable then un/subscribe that variable instead of doing it with the lambda directly
wait so there is actually no way to ignore parameters from an event?
you ignore it by not doing anything with it
well yes but I mean without having to pass them anywhere
I guess this doesn't really matter tho
the event is going to pass them no matter what
If you don't need them, don't pass them. If you need them, then pass them. You're not required to use the parameters . . .
even using the discard doesn't prevent it from passing the parameters, it just tells the compiler you don't want to actually use them
So what's the best way to learn how to code things in Unity as someone who's never coded before?
I can't seem to find any way to do it. I usually end up watching tutorials that end up being outdated
hence my previous coding problem
π
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
probably this
Not much will be outdated unless you are looking for a specific thing, like a Render Pipeline feature, or a very old Unity 5 tutorial 
Hi,
I'm doing a very simple school project where I've made a blackjack game and now need to make it multiplayer. The game is fully functional as single player. But how to make it multiplayer confuses me with how many different solutions I see out there.
Is there by any chance anyone willing to help me?
Thank you for your time and have a good day π
do you want it to be online multiplayer? if so, it is suddenly a very complicated project, and I wouldn't recommend it unless you already have a decent knowledge of unity and C# and are willing to learn a lot. for that, I would recommend making a post in #1390346492019212368 and ask there instead. If you want local multiplayer (not sure how that would work with blackjack) then it's far simpler.
if i have a script using InvokeRepeating to repeat a function every X seconds, what happens if i disable the gameobject that script is attached to?
does it stop repeating or does it keep going?
maybe not the answer you want but the best answer is to stop using invokerepeating
and use something like a coroutine which has better documentation and results online
It stops
ive just realised a slight problem lmao
ive got an object disabling itself in a script and then that same script is to reenable it later
except its disabled so nothing happens
oop
is there a way to quickly delete all the points on a linerenderer?
if you set the array size to 0 iirc
Could anyone teach me why unity allows code written like this?
CBUFFER_START (UnityPerMaterial)
TEXTURE2D (_MainTex);
SAMPLER (sampler_MainTex);
float4 _MainTex_ST;
CBUFFER_END
What do you mean "allows"? It's HLSL for making shaders
bc it's not c#? I assume that's what you're referring to
"allows" means texture declaration is allowed in cbuffer declaration scope without error, which should be impossible
this channel is primarily for c# scripting, for shader stuff perhaps ask #1390346776804069396
using UnityEngine;
using UnityEngine.InputSystem;
public class DoorScript : MonoBehaviour
{
public Transform mainCamera;
public Transform player;
public Transform door;
public InputActionReference interact;
public float openSpeed;
public float closedSpeed;
bool opened;
RaycastHit hit;
Vector3 currentRotation;
Vector3 openTargetRotation = new Vector3(0, -135, 0);
Vector3 closedTargetRotation = new Vector3(0, 0, 0);
LayerMask layermask;
void Start()
{
layermask = LayerMask.GetMask("Door");
}
void FixedUpdate()
{
currentRotation = transform.eulerAngles;
if (Physics.Raycast(player.position, mainCamera.TransformDirection(Vector3.forward), out hit, 2, layermask))
{
Debug.DrawRay(player.position, mainCamera.TransformDirection(Vector3.forward) * 2f, Color.yellow);
if (interact.action.IsPressed() && !opened)
{
opened = true;
}
else if (interact.action.IsPressed() && opened)
{
opened = false;
}
}
if (opened)
{
currentRotation.y = Mathf.LerpAngle(currentRotation.y, openTargetRotation.y, openSpeed * Time.deltaTime);
transform.eulerAngles = currentRotation;
if (transform.eulerAngles.y >= -120)
{
opened = false;
}
}
if (!opened)
{
currentRotation.y = Mathf.LerpAngle(currentRotation.y, closedTargetRotation.y, closedSpeed * Time.deltaTime);
transform.eulerAngles = currentRotation;
if (transform.eulerAngles.y <= -15)
{
opened = true;
}
}
}
}
(Watch the video for context)
okay
Mic was not working lmao
ill repost this over there
I want the door to just go open, then when the eulerangle.y is -120 or less it will be able to close, and the same for the opposite its just greater -15
you generally shouldn't use eulerAngles to store state
why not just keep track of the state yourself?
ah, because it's wrong lerp
what is the bongo cat thing you have on the bottom right i want that
Applying lerp so that it produces smooth, imperfect movement towards a target value.
what you just said. Thats what it is. Bongo Cat on steam
"lerp" stands for "linear interpolation"
you're using it "wrong", in that you're giving different arguments that make it not a linear interpolation. it looks nice on the surface but has inconsistent and undesirable behavior once you get into the math
it'll technically never reach the openTargetRotation
you just.. wouldn't use it, tbh
then what would I use?
there are replacements here, but iirc they also asymtote the target (meaning mathematically they might never reach it)
but at least with that, you get consistent times
that solves one of the issues
for the asymtotic behavior, you could use an epsilon to snap
you might want to consider using a coroutine for this to make the logic much simpler
have you heard of those before?
didnt the other guy explain that like last week?
no clue, i barely remember you
you'll have to search your message history for that lol
but coroutines basically let you have a contiguous block of code for logic that runs over time, rather than having a function called multiple times for each timestep
it was when we were rude to eachother
don't remember that either.. i don't really remember people here
lmao
for example, here's how you might do it with normal lerping (no smoothing)
IEnumerator Open() {
float elapsedTime = 0;
Vector3 rot = transform.eulerAngles;
while (elapsedTime < openTime) {
rot.y = Mathf.LerpAngle(closeAngle, openAngle, elapsedTime / openTime); // slerping quaternions might be something to consider too
transform.eulerAngles = rot;
elapsedTime += Time.deltaTime;
yield return null;
}
opened = true;
}
that's normal tbh
coroutines definitely use stuff that you might not see in other game logic
there are probably guides/explanations online you can search for
You could use an animation curve in conjunction with the third parameter if you want easing or some other functional rate of change.
oh that's also an option, forgot about that
you don't get asymtotic behavior with that
Hiya im having an issue getting my button to work. I have a button with sprites attached to it and i want to be able to press the button and have an animation play for said button, but ive looked at tutorials and such and i dont get how their buttons just work with no "onClick" or anything like that so i would like some assistance please :)
buttons have UnityEvents, you have to assign them
how would i go about that?
look in the button component in the inspector, there's an "on click" there - that's a unityevent rather than a message
click the plus icon and assign the component you have there, and set it to call OnClick
Look at the example on the docs
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/UIElements.Button.html
var button = new Button { text = "Click me" };
button.clicked += OnClick;```
which of these sections lets me call OnClick
uhhh don't think that's the right one
"On Click" kinda hints that it's the Unity UI one
Did you select a Button instance or prefab? The instance would have your instance members
have you added the component here #π»βcode-beginner message to a gameobject?
Yeah, it doesn't look right now that you've mentioned it..
yeah, i added it to the button
what's the component called
no, what did you name the class lol
then you would pick the section that says Dice
mb im confused on what a class is, im still a beginner to this π
it's the thing you put code in, the thing declared by class near the top of the file
π
which one of these would allow me to call the method
(which is private btw)
shoot, do they need to be public? ive forgotten
i believe so π
the issue of firerate of a weapon depends on FPS really boggles me
so I made it that shooting is in a Fixed Update but I think that made cooldown quantifiable
so I have no idea how people do treat this issue in general, got any ideas?
firerate is not fps dependent per se, unless you code it that way
yep, I meant basic solution with using Update and a timer of sorts
so yeah I would appreciate if anyone got an advice on how to make firerate framerate independent
what do you currently have?
weird solution from my last project
player input is read at Update
shooting is at FixedUpdate on a timer
and a timer also makes into account how time steps not matching firerate and reducing time till next shot by that delta
there are bit more stuff bit it's not relevant I think
it works but I figure I might ask if there are better ways to do it
because what I did looks suspiciously overcomplicated
google has a lot of results when you search "unity frame independent timer"
Sounds pretty standard to me
iirc I failed to find a good solution so I made that
My standard approach is like this #π»βcode-beginner message
If spawning projectiles it can place them at different positions based on the idea of calculating when in the intra-frame timing it should have spawned.
that's like what I did but doesn't look overcomplicated, nice
I thought of doing that too but that looked even more overcomplicated
well it's nice to know I am on the right path, thanks
I would assume Unity got something premade for such things but yeah
Unity doesn't really pre-do that kinda stuff
it's too situational for how small it is i think
meanwhile they got gimmicky stuff like smoothDeltaTime
Thatβs something where thereβs not too many major ways people would want to implement that
im having an issue with my code. it's supposed to draw a raycast from the camera that follows the cursor. it does move according to the cursor, but it isnt drawn from the camera, just a random point in the scene. any ideas how i could fix/debug this?
it's being drawn from transform.position presumably that transform isn't the camera transform
change that to cam.transform.position
when you use transform in your code, that is accessing the transform for the gameObject that this component is on.
Hi, i was hoping to see if anyone would be able to spend some minutes teaching me how to make my enemie AI on my game
tysm its working now
Not likely, this server isn't for tutoring in such a way. You need to ask specific questions
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #π±βstart-here
okay, it draws it out from the camera, but its kind of weird
it shoots at a different angle than from what the camera is actually looking at
did you change both transform.position to cam.transform.position ?
no, i didnt. i completely forgot about the second one haha
i fixed it though
tysm for helping
hey yall, quick rigidbody related question.
so i had this issue of a player clipping through a corner with no effort, i've tried:
- setting collision to the various amounts of Continuous collisions (continuous dynamic, continuous default, etc.)
- made the colliders thicker
- checked the physics collision settings (not that there was any point to that, the collisions WORK it's just that any corner is clippable)
- made sure that i'm moving the character using the physics commands and not something like Transform
- made sure that the physics controls are in FixedUpdate
This is the code that i ran before i tried another fix which worked out
Vector3 targetPos = rb.position + move * runSpeed * Time.fixedDeltaTime;
rb.MovePosition(targetPos)
This is the fix i did, that worked out
Vector3 targetVelocity = move * runSpeed;
rb.linearVelocity = targetVelocity;
though, i've seen many guides that still use MovePosition, am I missing something here? Because i wholeheartedly believe in using MovePosition instead, but for some reason it's just not working out for me
MovePosition ignores colliders. It works in most cases because after MovePosition the physics engine detects that the player is inside a collider and pushes them out, but sometimes you get that kind of tunneling
MovePosition is mainly supposed to be used with kinematic rigidbodies only
ahhhh aha i see, also if i want the player to be pushed around (say, another player punches them to knock em around) then I don't want the player to be kinematic right?
and if i don't want the player to be kinematic, then using the linearVelocity method would be better for this case right?
linearVelocity or AddForce are the safest ways to avoid that kind of edge cases, yes
If you want outside forces affect the player (punching etc) then AddForce is the easiest or you need to calculate the forces manually
yup got it, thanks
Am I the only one who is afraid to start Unity or any other game engine? Because it is important that you choose an engine that you believe in.
Because it is important that you choose an engine that you believe in
I think you're way off base here.
You should try them all, get familiar with them all as tools, then choose the one that suits you.
You're not locked to using a single game engine for your entire life
Ofc for a single project you may need to stay on the engine for various reasons but there's nothing stopping you from using other engines
Totaly should just wouldn't recommend godot their snake_case functions scared me off -_-
Well that plus their lack of proper intellisense for using c# and poor documention for c#
huh yea their code docs are a lil funny
snakecase is superior
Can someone explain to me like I'm 5 what a raycast is? I still don't understand.
So It's a line that points from the gameobject towards a direction to detect whatever has hit it?
fire out invisible line till it hits some physics collider
you can perform a raycast from any position you want and it can go in any direction you want for the distance you want
Snake_Case is awful, being forced to call functions with underscores between each word just adds to my already slow typing speed
But the game object is the origin?
it can be but doesn't have to be
you specify the origin and direction when calling the Raycast method
So what exactly would raycasts be useful for? I assume menu buttons?
A many of things one common one is checking if you are grounded
well ui interaction is done for us by unity
or if a gun firing some bullet hit anything
well yes, raycasts are used by the EventSystem to interact with your UI so you don't need to use them directly there, but it's also useful for things like ground checks, or just checking if a collider is in a specific direction from a specific point
(often known as hit scan by players)
Oh i know what that is
irrelevant but curious what would it be called for a bullet without any drop but had travel time?
DbContextOptionsSqlServerExtensions
vs
Db_context_options_sql_server_extensions
I choose the one not to squint at
rust uses snake case but c# already has a set standard so lets stick to that
it's typically hit scan vs projectile. and that's still projectile even if it doesn't have any physics interactions (i.e gravity). projectile really just means "object with travel time" as opposed to hit scan's "instant check if hit"
I just use standard, but I get to the point where adding more than 3 variables syllables to my class names halts my progress lol
Coming from C, snake case reminds me of macro definitions. For me, the underscore often blends in with white space when having to look at multiple lines (50+) of declarations that have got similar names.cs foo_bar_baz qux_quux_quuz; foo_bar baz_qux_quux_quuz; foo_bar_baz_qux_quux quuz; foo bar_baz_qux_quux_quuz; foo_bar_baz_qux quux_quuz;Bad naming convention and non consistent patterns are the true villains though.
using UnityEngine;
using UnityEngine.InputSystem;
public class mouseScript : MonoBehaviour
{
Ray ray;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
ray = new Ray(mouse_pos, new Vector3(0.0f, 0.0f, 1.0f));
CheckForColliders();
Debug.DrawRay(ray.origin, ray.direction, Color.red);
}
void CheckForColliders()
{
Debug.Log($"{ray}");
if (Physics.Raycast(ray, out RaycastHit hit))
{
Debug.Log(hit.collider.gameObject.name + "was hit!");
}
}
}
i have this script attached to main camera and i don't really understand why it's not recognising hits onto colliders
Well you're not really showing many details here but seeing as you have a GlobalLight2D I'm going to guess you have a 2D game and you're using 2D physics?
What kind of colliders?
oh wait nvm, they don't have any collider on them, the ducks...
But your code is doing a 3D raycast
And yeah - you will definitely need colliders. Just make sure you're using the right kind of raycasts (2d or 3d)
Also if you're trying to detect mouse clicks here I would recommend either:
- Using the event system for this instead, e.g. IPointerEnterHandler/IPointerDownHandler
- Using Physics2D.GetRayIntersection instead of Raycast
seems unintuitive ngl
2d is basically 3d without one dimension, since my directional vector is 0.0f, 0.0f, 1.0f, doesn't that basically do the job?
i just wanna know whether my mouse is on a collider or not...
no, they are two completely separate physics engines
O_O
See my recommendations here: #π»βcode-beginner message
raycasts use physics engines...why?
The specific raycasts you are trying to use do
you're using Physics.Raycast
that's clearly part of the physics engine
Unity uses Box2d for 2d physics
Because its the physics engines that provide raycasting functionality. Its performed against physics colliders
There is a function in Monobehaviour called OnMouseOver that does just that. Which is called when the mouse is over that object's collider or ui
OnMouseOver doesn't work with the new input system
that's why I recommended IPointerEnterHandler/IPointerExitHandler
Really? Didn't know though i also havent touvhed the new input system yet
Yep, check the docs you linked:
Note: New projects created with this version of Unity are pre-configured to use a version of the Input System that doesn't support this callback. To support this callback in your project, you can change the Active Input Handling setting in Player settings to either Both or Input Manager (Old). However, doing so is not recommended as the legacy Input Manager is nearing the end of support and Input System is the recommended solution for new projects. For more information, refer to Migrating from the old Input Manager.
wait a second, how would you make a ray go into the screen without using the Z coordinates O_O
Just what I wrote above
Using Physics2D.GetRayIntersection instead of Raycast
And nobody says not to use the z coordinate
you should be using Camera.main.ScreenPointToRay(Mouse.current.position.value) to create the ray
ahh shiii, now i gotta go find camera documentation instead of physics for raycast
what
am i doing it in a dumb fashion or smth? is this not how you guys get to know about methods you didn't know a type had or smth?
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.value);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, distance, layermask);```
well you said "instead of physics" so I thought you were getting confused about the fact that you need both of these things together
ahh ok
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Physics2D.GetRayIntersection.html
so, if i am not wrong, GetRayIntersection is supposed to return some kind of an integer when it detects a hit, and then RaycastHit2D is a class which can somehow use that integer?
the documentation has nothing related to exactly what the integer is gonna be though

SCroll down to the one that returns a RaycastHit2D. There are two different versions of the method
There are two methods. The first method that Returns an integer tells you what it is for. I would read it again . . .
The documentation says exactly what the integer is for that one
yes that's the one that returns RaycastHit2D (that you just deleted)
sry, some sort of bug happened and the msg i wanted to upload didn't happen, that's besides the point. what is the int gonna be? there's no range nothing
it says right there
"The number of RaycastHit2D results returned"
that version of the function is for getting multiple raycast hits
you want the one that just returns a single one
which, like I said, is there if you scroll down. You posted a screenshot of it a second ago
ya, i got that
just use that one
i am rly dumb. what does this even mean π
does this mean that if it were to hit 2 or 3 colliders, it would return 2 or 3
yes...
sometimes we want to do a raycast and get the first thing hit
other times we want everything that the ray hit on its path
If you look at the parameters there's a results parameter which is where the RaycastHit2D results actually get put into
the return value just tells you how many it put in the list
ya i saw that, i don't want a list though
right so stop focusing on the list one
Then you wouldn't use that one
ok i think i got it, so... if i am not wrong, the RaycastHit2D returned has info regarding the collider it hit which i can access using its various properties
whats the state on Unity and multithreading support?
last time i checked was almost null
Most unity systems make use of background threads and jobs.
As for your own code, it's up to you. You can use jobs system or any of the C# multitgreading features.
And it was like that for a while.
There are more things can be done/used in unity c# jobs
And ECS has good support for using jobs
most shit isnt thread safe, i dont mind doing my own synchronization points, but unity seems to be checking and preventing to use api code on non main thread
Most api is main thread bound, but it's rarely the actual bottleneck anyway. And there are reasons for it to be main thread bound. Most engines have such limitations. For example, unreal engine.
is there a chance anyone can help me with this bug? i have no idea why its happening and have been trying to fix it for about two weeks now
read the stacktrace (the bit below this error) ... it points to the class and the line where this error is
not even sure i should be asking here so if i can ask somewhere else do tell me
any workarounds?
Don't make unity api the core of your heavy processing work.
the line is the line in one onenable
and when i comment it out its the other one
Do heavy calculations off the main thread and then call the necessary unity api. Or use job compatible api.
most likely in your OnDisable you need to be doing:
var em = EventsManager.instance
if (em) {
em.dialogueEvents.onEnterDialogue -= EnterDialogue;
}```
Then there's no EventsManager present at the time of this code running
As for the OnEnable - you have an execution order issue
Because your instance is probably being assigned in that class in Awake, which is running after this
need help these always appear:
MissingReferenceException: The variable m_Targets of GameObjectInspector doesn't exist anymore.
You probably need to reassign the m_Targets variable of the 'GameObjectInspector' script in the inspector. Parameter name: componentOrGameObject
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <7b8172fcdd864e17924794813da71712>:0)
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <7b8172fcdd864e17924794813da71712>:0)
UnityEditor.PrefabUtility.IsPartOfVariantPrefab (UnityEngine.Object componentOrGameObject) (at <8081513dc2364383b8289d30d2169b2e>:0)
UnityEditor.GameObjectInspector.OnEnable () (at <8081513dc2364383b8289d30d2169b2e>:0)
is there any way to fix that?
i also thought it might be smth with what runs first but wasnt sure how to test it
dont enable the gameobject with this code on before the eventmanager
Logs or debugger + breakpoints.
this is the even manager im using
it doesn't help
just making an instance of the dialogue events
how do i use the debugger?
script execution order settings is one way
You usually want to return early and perhaps even Destroy the duplicate instead of letting it assign to Instance too
another way is a lazy-assigned Instance property for the singleton (but this can be slower)
but it doesnt let the game run anyway cause i have debug.LogError
Its not throwing an exception, its just logging an error
so code execution continues
if you actually threw an exception there it would return early
but the game just stops running doesnt that stop the code?
sorry, why do you think the game stops running?
or rather its paused
unity pausing on errors is just to aid in debugging and is an editor only feature
do you mean its a good coding principle in general?
me neitherπ
im not just loggin text though im making my own error
Debug.LogError("I don't stop anything!");
File.Delete("C:/"); //ohh no!
sure but it works the same way in unity doesnt it
it does not
logs are NOT EXCEPTIONS
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/
^ read and learn
compare these
Debug.LogError("Error-formatted log");
Debug.Log("After LogError");
``````cs
throw new Exception("Thrown error");
Debug.Log("After throw");
no need to be mean about it dude i am new to coding in unity thats why i came to code beginner channel
i don't mean to insult or anything, but
sure but it works the same way in unity doesnt it
my man you are arguing against us
i said this already so i want to get over the most important point π
saying "read and learn" is not anything mean .
coding is hard and confusing so reading the lang documentation is the best way to learn
you have a false assumption, and that's a pretty normal/human thing to do
what's important is that you can discard that assumption when you have reason to believe it's wrong - for example, someone more experienced tells you that the assumption is wrong #π»βcode-beginner message
what about it?
your original question does have an answer btw #π»βcode-beginner message
the singleton needs to be initialized before other stuff can use it
there are multiple ways to achieve that, carwash gave one of them
should i make my object inherit from monobehaviour then instead of making it with the even manager?
im very confused here
...huh?
which object are you referring to here
you shouldn't have anything inheriting from eventmanager
whatever gameobject this code is on, should start disabled.
Once the eventmanager as initialized, then this gameobject should be enabled and you will not get the NRE
the dialogue events
speaking of.. i have a system that has both scripts boot generally at the same time..
i really don't feel like changing the script execution order.. is it standard or common to use a
while statement in update and a flag to assign it when its available and then flag it as found to avoid continueing looking?
im not a pillar of gamedev, ive no way to know if that's standard/common lol
i dont
it's certainly a way to do it
script execution order can quickly get out of hand.
having a while loop in Update sounds like a poor / lazy way to do it.
private void TryAssignInteract()
{
var inputManager = Object.FindFirstObjectByType<InputManager>();
if (inputManager == null)
{
Debug.LogWarning("[InteractRaycast] No InputManager found in scene.");
return;
}
var actionRef = inputManager.GetAction("Interact");
if (actionRef != null)
AssignInteract(actionRef);
}``` ie
is it.. not already a MonoBehaviour?
it just doesnt inherit from anything
how's it getting, "activated" per se then?
cause im creating it in events manager
is something else calling initializing/calling methods on it?
ya, thats why i asked.. feels a bit lazy, but i not sure of how to do it other than changin the execution order and having my inputmanager run b4 the rest
ah, i see.
An actual manager that controls the loading and enabling of things
yea, i guess ur right
i solve this by having my singletons in a central "System" scene, which then loads the actual main menu scene and such
i was just being lazy lmao to be honest
i had thought of making another manager but thought i could find a cheeky way
the way im doing it is im creating an instance of my object in the events manager then with the dialogue events manager im calling a method on the dialogue event
@minor quiver ok, so DialogueEvents doesn't really matter here. what does matter is whatever class is trying to access the EventsManager.Instance, which would be.. whatever class this is #π»βcode-beginner message
but it says that i havent set a reference to it
For apps in my last job I did it this way. Had a scene called 'Managers' which was loaded before everything that needed them
right, because it's probably getting initialized before EventsManager - what carwash mentioned
and how do i get around that?
Share the full error, so we can see the stack
like i mentioned before, carwash gave one way to do it #π»βcode-beginner message
do you mean this?
is this code from 'DialogueManager.cs' ?
yes but im not sure what he meant
ok, then ask instead of pretending the message doesn't exist
yea
(we aren't psychic - we won't know if you understand or don't understand if you never say anything)
i have 5 people telling me things its overwhelming
βοΈ
this would be a straightforward-ish fix, but not super scalable - a more scalable (but more complex) fix would be more akin to #π»βcode-beginner message
the only thing from what you told me that i know so far is singleton
it's 2 right now - if it seems like more, this might be a good time to take a little breather
i only have one scene though will it still work the same way?
carwash elaborated here
#π»βcode-beginner message
is there any terminology or wording there you don't understand?
if/once you understand each term on its own, do you understand it as a whole? (don't worry about the code yet, just work on understanding the concepts for now)
you might be misunderstanding
the current fix carwash proposed doesn't involve other scenes
my answer to spawn's question would involve creating a new scene for the singletons - that's a separate solution
private IEnumerator SubscribeWhenReady()
{
while (TickManager.Instance == null)
yield return null;
fastTick = TickManager.Instance.AddTick("FastTick", 0.25f);
slowTick = TickManager.Instance.AddTick("SlowTick", 3f);
fastTick.AddListener(OnFastTick);
slowTick.AddListener(OnSlowTick);
}``` crap... i've found i do it many different places..
time to actually sit down and restructure my setup
-# #hooray
working on that right now
so i enable the dialogue events manager in the events manager so im sure it loads first is that it?
or did i understand it wrong?
that would be one way to do it
the basic understanding is there yes..
it's not the only way, but you're on the right track
the thing ur calling methods from must be a thing before the other thing is a thing
does just enabling a disabling items in unity work in a way that helps me with this
so like can i just enable and disable it from the editor or smth?
ya, when u enable a script its OnEnable() and Awake() run.
ohh from the editor? well thats a hacky way.. that wouldnt happen in the game
woudlnt help u in the long run
if you disable (or deactivate) stuff outside of playmode, they'll start as disabled/deactivated when you enter playmode, and then you would have some process to enable/activate them
what loads first OnEnable or Awake?
Awake first
then i shouldnt be getting the error
it's not all awakes first
cause im making the thing in awake and then calling it OnEnable
https://docs.unity3d.com/6000.2/Documentation/Manual/execution-order.html this might help you to bookmark
Awake is only called before OnEnable within the context of a single script. If you have multiple scripts with these methods, both Awake and OnEnable can get called for one script, before both get called for another one.
Start is always called after Awake and OnEnable for all scripts
i shouldve been clearer, that's on me - Awake is before OnEnable for each gameobject
use logs to visualize when things happen
if you put a log w/ the name of the script in the Awakes() OnEnables() etc.. u can see in the console which calls when
right now you have them on different gameobjects, so there's no guarantee that Awake on one will be called before OnEnable of another
let me try start then ill get back to you on that
good luck π
Yeah, if I have this problem usually I move the dependency to Start rather than Awake, then if I still have problem there is a script execution order you can adjust
last resort imo
like carwash said.. it gets messy and out of hand quickly
especially if thats your go-to solution
Using Start() to register delegates/ actions generally isn't great .. especially if you're going to be enabling/disabling the object.
i've done it before for GameManagers and stuff.. (things that are persistent thru the whole game) nothing wrong with having them have priority in the execution order
i think start wokred but it looks weird in the code now cause im unsubscribing from it OnDisable
i am i think
whats wrong with that? thats where i unsub from everything
how do i write code here like this btw?
subbing in Start and unsubbing in .. well anywhere, will mean toggling the active state will result in not being subbed again after the very first time
!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/
π 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.
might be easyer than screenshots
βοΈ inline code section
Oh we are talking here about delegates? I missed that part, sorry. Then yeah it's better to do that OnDisable and unregister OnDisable to be sure you don't call the method on the inactive instances
those are not quotation marks btw
good point
the tilde key.. the thing you'd use for bring up a console in games
found it
using UnityEngine;
public class DialogueManager : MonoBehaviour
{
private bool dialoguePlaying = false;
private void Start()
{
EventsManager.Instance.dialogueEvents.onEnterDialogue += EnterDialogue;
}
private void OnDisable()
{
EventsManager.Instance.dialogueEvents.onEnterDialogue -= EnterDialogue;
}
im doing this now
aye.. look at you.. leveling up πͺ
Usually I just delegate from the manager on instantiation and let the manager handle it all, but delegating in start implies a singleton and I know people are iffy about that
and seems to be working i think
are you toggling the active state of this gameobject during gameplay?
i think so yea
i both spawn and call it while playing
if you are, then it will not work the second time you enable it
lol.. had trouble finding the script execution order page on the docs π€£
they changed it.. or added more documentation or im just ignorant
i remembered it being the first result.. but meh, small potatos
i dont think im disabling it before the game stops
wait let me test it
you just said you think you are... so.. go make sure
|| dont assume anything ||
(they aren't tildes, btw. that's ~. they're called backticks/backquotes/grave marks/grave accents)
drunk dash
it's (often) on the same key as the tilde.
Does this have any downsides? Because that's a simple solution I never thought about.
im never exiting the dialogue cause i couldnt test it up until now with that bug so for now no problems
it only ever subscribes.. its meant to persistent thru the entire game..
so for that use-case its fine i believe
i would like to know if you have any better ways to fix it than start()
(1 extra if logic that it runs in Update) <- only downside i see
cause i do plan on exiting at some point
i feel like it'd be a great place for race conditions to sneak in ngl
yes, the way I said from the very begining
i have no idea what it is though
which part exactly?
does it let me activate an object first before another
you never answered my question for clarification
So isn't the 'OnEnable' and 'OnDisable' problem only at the scene start when not all objects have yet been instantiated? In that case adjusting the execution order should fix the issue, right? Or am I missing something?
you also, like, did get it here though?
#π»βcode-beginner message
you generally shouldn't overuse SEO
as a concept but i have no idea how to code it
SEO?
I don't understand what you don't understand. I can't get in the beginners head ..
it's simple.
EventManger is active in the scene.
DialogueManager is not active in the scene.
EventManager initialises.
Now at some point you need to have something to enable the game object with DialogueManager on.
cool, but that's already quite a bit more than "no idea what it is"
script execution order (may also refer to search engine optimization in other contexts)
if i find a way to do that ill come back to you but i have to go now thanks for the help
i have like one idea on how to do it
In a game I'm developing I have a manager that just has a list in.
I ittirate over the list and enable the assigned gameobjects in the order
Is there any code that allows us to improve fps ?
dont have that many objects to do that too but that helps
having it as a list just makes it more robust because you don't need to add any more code if /when you want to add more to the list
Hmm, is there any reason for that?
to be honest, im kind of parroting advice here - i haven't had much reason to use SEO to begin with.
from my own viewpoint (take with a grain of salt, since i haven't used it) it's kind of an external thing to the rest of your codebase, and it's somewhat opaque and may break subtly if you make a mistake with it. putting dependencies in code makes it easier to visualize or modify
how to make a car climb steep slopes but at the same time it wasn't too fast, I'm just trying to make a game with an off-road vehicle?
Thanks, that makes sense! I generally try to avoid it too, but it always seemed like a 'good' emergency tool where everythign else seems a bit complex, though honestly I dind't have reason to use it for a while now either - I always find there is a way to code it.
Any ideas as to why my fps would be tanking Iβve put out 2 demos and it seems to be an issue with the game
You need to profile it to find out. Google -> how to use unity profiler
Ok π
Thanks
is this LayerMask layer = LayerMask.GetMask("Enemies"); supposed to be this or this
they are not the same: https://docs.unity3d.com/6000.2/Documentation/Manual/class-TagManager.html
Sorting layers are different
also, you can serialize LayerMasks to avoid magic strings
(the resulting dropdown should make it obvious which one it's referring to π)
that's a great idea, btw what do you mean by magic strings?
seamingly unknown code which doesn't explain itself?
hardcoding strings that are specific things
specifically the "Enemies" string in this case
other examples would include animator parameter names or resource names or gameobject names
i thought it was self-explanatory but oh well...
they're things that would break if you made a typo or renamed something (without changing all the corresponding strings), and since they're strings instead of identifiers, IDEs can't really help check with static analysis or rename symbol refactors
similar concept is magic numbers, hardcoded numbers that mean specific things
Im trying to use Unity Events to make the Player's health make the Health Bar update...but, how can I pass data through a Unity Event?
I want to pass the health_amount through the event.
unityevents have generics, so like, UnityEvent<int> for one that passes an int
I tried doing this:
public class Player : MonoBehaviour
{
public float health = 10;
public UnityEvent<float> onHealthChanged;
void Damage()
{
health -= 1;
onHealthChanged.Invoke(health);
...
But when I try to connect the signal in the inspector, it asks me to set a value:
You need to select the function from the Dynamic Parameter list at the top
not the Static Parameter list
(in the dropdown)
yes
aight, the thing is working now. any ideas as to what i need to look into so as to create a temporary object at my mouse position when the user clicks on the unit they wanna deploy?
- Always have such an object there and just show/hide it
- Use Graphics.DrawTexture or RenderMesh
- Instantiate an object when mouse enters and destroy it when mouse off
hi. me again.
i have a time thats supposed to count down from 5 to 0 but stop if the bus is no longer in the selected zone. imma make it so the user has to hold down the brake too later.
my issue:
the timer goes instantly from 5 to 0 as shown in the video. why is this?
code:
private void OnTriggerEnter(Collider other)
{
Debug.Log(other.name);
if (other.CompareTag("Bus"))
{
Debug.Log("Boarding...");
isIn = true;
while (timer >= 0 && isIn)
{
timer -= Time.deltaTime;
Debug.Log($"{timer} {isIn}");
}
if(timer <= 0)
{
foreach(var p in peopleInQueue)
{
BusManager.SeatMe(p);
Debug.Log("Boarded");
}
}
}
}
OnTriggerEnter runs exactly one time when you enter the trigger
the whole idea of having a loop in here makes no sense
your entire loop is, of course, running instantly
oh so should i make a method for it?
method or not is irrelevant. If you want to wait for future frames you need either a coroutine or to involve Update or FixedUpdate
Admin unity
so if i do this in fixedUpdate, do i make it set a boolean to true or false based on when the bus enters/exits the trigger then do the loop?
that's an option, sure, but you wouldn't use a loop explicitly in your code
FixedUpdate is implicitly in a loop
over time
so an if statement instead of a loop?
yes
in that case you could also just use the timer do double duty as the state too rather than a separate bool
ahh understood. i will have a play. thanks
ahh right
like this:
private void FixedUpdate()
{
if (timer > 0)
{
timer -= Time.deltaTime;
Debug.Log($"{timer} {isIn}");
}else
{
foreach (var p in peopleInQueue)
{
BusManager.SeatMe(p);
Debug.Log("Boarded");
}
}
}
private void OnTriggerEnter(Collider other)
{
Debug.Log(other.name);
if (other.CompareTag("Bus"))
{
Debug.Log("Boarding...");
isIn = true;
}
}
right got it. thank you!
you'd also set the timer in OnTriggerEnter
ah yes
so i used spriterenderer instead of what you suggested because that's what i basically have been doing up until now but it says that if (spriteToRender.sprite != null && !(Mouse.current.leftButton.isPressed)) is referencing a null value
A tool for sharing your source code with the world!
spriteToRender may be null
In fact it's definitely null
because it's private and you never assigned it to anything
i mean yeah, but then that doesn't make sense as to why its popping
NullReferenceException: Object reference not set to an instance of an object mouseScript.Update () (at Assets/Scripts/mouseScript.cs:27) this msg
Of course it does
it's null
and you're trying to dereference it
that's precisely what a NullReferenceException is
Agreed
didn't i do this though spriteToRender.sprite = Droplet;
you can't do spriteToRender.ANYTHING
because spriteToRender itself is null
you have to assign that reference (spriteToRender) before you can use it
Also spriteToRender is not a good name for that variable. It's a SpriteRenderer, not a Sprite
aiaiaia
so, i need to go into unity and assign it the Sprite Renderer component by first setting it's modifier as [SerializedField]
Yes that would be one way to assign the reference
Understanding null reference exceptions complete! β
Until they pop up again -_-
Once you know what it really means you can better debug and fix them
Is this intended?
π no
i wanna drag and drop those units onto the game screen
A tool for sharing your source code with the world!
Kinda hard to read since blazebin hates my phone and bugs out but i think the problem is you are changes the position on all 3 axis which moves it really close to the camera
yeah, how did you know that's what's happening without seeing the video though
Experience!
I read the code
if you're working in 2d you generally shouldn't touch Z positions, and work with Vector2s
This too lol
the camera should usually be at Z -10
i could change mouse_pos to Vector2D, dunno whether that will fix it though...
what am i doing wrong?
Use vector2 instead
oh wait, i think i got it? spriteToRender.transform.position = mouse_pos;
did it, same thing
You are setting the mouse_pos as Vector3, which includes the z axis. Technically it moves ur object close to the screen
Why does main camera have a sprite renderer?
the mousescript that i am currently using (which is attached to camera) requires the sprite to be made so...
i could reference to some other object in the heirarchy...
yeah no, there is some deep misunderstanding there
Right you should have that sprite renderer be on the object you wish to move not the camera
Since right now when you move that sprite renderer to move position it moves the camera object as a whole there
ya...that's what i said, this is the problem, the transform.position moves the gameObject, in this case, it's the camera
you need some separation of concerns there
The problem is less of that statement but instead that you have the sprite renderer on your camera
what is spriteToRender even for if it's just on the camera
are you just storing the sprite there for some reason
if that's the case, you could just store the sprite itself
The transform.position of any component is the transform of the game object itβs attached to
U are trying to move the camera itself
so...i currently have the above attached scripts working in tandem. i remember thinking that when i wanted to build a way so that the mouse could drag and drop stuff, delete tower and stuff, upgrade towers (maybe)...that i would need to attach it to something completely unrelated to the gameobjects which have sprites and other stuff on them. so i attached it to camera. Now that, the mousescript finally recognises when i click on the deploymentUI, i want it to load up the sprite which the mouse is clicking on too, that's why, i attached a sprite onto it.
now, in order for the sprite to show up at the mouse's location, i am trying to change its position...that's why i initially used transform.position, not realising that that would change the gameobject the sprite renderer is attached to
U should treat the draggable sprites as separated objects
shall i tell you the logic that i have in mind to spawn and destroy them?
So what I understand here is that u want a tower defense system with draggable sprites that will spawn the associated objects like towers, turrets .etc.
Itβs like packing a candy. U have the wrap as the sprite, the candy inside is the associated objects. They together form a completed object. And u can easily reference connected parts in the script with prefabs and components,β¦
should...i??

@hot wadi
i realised, i don't need three if blocks, just two will do with a nested if-else logic
So itβs like a customized cursor

at the end of this, i want the cursor to just manage loading up sprites and deleting them on the game screen
Ok, what if u need different sprites for different objects? U are gonna reference them all in the camera script?
yeah...
is this a bad way of doing it
Then how are u gonna check what object gets to assign what sprite on the cursor?
what
no object assigns anything...
i check the tags, match em with a sprite, then make sprite rederer's sprite become that sprite
you could skip that second step by just having each thing provide the sprite directly
elaboration needed
what do you mean by each thing
the things you're clicking
instead of hardcoding each unit with a tag, have a component to supply the data
you could even have an SO that when you assign to the component it sets the spriterenderer of the button automatically too
Each object owns their own sprite. That is the right way to do it. U should not use hundreds of tags to check what sprites matches what objects
so just...put the sprite i clicked on, onto the sprite renderer....using the gameObject returned by raycastintersectoin?
here's the thing though, these two are seperate, the one of the left is a parent of the right, how would i reference the droplet in the case that my mouse hovers over the box instead of the droplet? it doesn't have the droplet sprite attached to its sprite renderer component, it has a square assigned to it
Set them on different layers and let the raycast pick the dropletβs layer only
what are you actually raycasting for? a collider, no?
the ray won't hit the droplet though, cus if the droplet hits the black area, the droplet ain't hit
both the box and the droplet have a collider
whatever gameobject has the collider will be responsible for providing the info via a component
why tho
that definitely doesn't need to be a thing
suppose box does not have a collider, then when the mouse clicks on the black area, the ray hits nothing.
I just realized that u use collider on a UI object
i mean...how else would i know whether the mouse is or isn't on the ui object though
why does the droplet have a collider.
graphics raycasters are also a thing
good question, i think its redundant tbh
that's my point
then how do i get a reference to the droplet though
unitOneBackGround is the square in question and UIDroplet is the droplet
unitOneBackGround doesn't have the droplet sprite attached to it
so if ray does hit it, what the RaycastHit2D references ain't the droplet sprite, it's the square sprite
make a variable to hold a reference
hold a sprite or hold a spriterenderer
pretty straightforward
ya but like, how do i get the reference to the droplet, not the square
have you like. never dragged components around before
make a new component as the thing managing the clicks (replacing the tag check)
that component would have a sprite/spriterenderer field (choose one)
if sprite, drag the sprite you want to use as the preview into that field
if spriterenderer, drag the child object that has that sprite into that field
so...i attach a new script to it, and reference the droplet into its [SerialiseField] sprite renderer
The easiest way is to have a script attached to the yellow box with a SpriteRenderer reference and the collider or however u use to make it detectable , then u can drag the Droplet reference in that box
Btw u have to set that reference public so other objects can get it
βpublic SpriteRendererβ
[SerializeField] without access modifier only makes it βprivateβ
Thanks. Just take a break after this. U might have been overwhelmed.
ya...just adding simple features are taking me a long time, hopefully in the future, i get faster
atleast my initial dog implementation works. now i just need to implement what you guys said
I have been hearing things like "ECS", "DOTS", and "Burst".
Are these like different ways of programming in Unity? Is this relevant to a beginner?
Are these like different ways of programming in Unity?
they're different tools that affect the specifics of your code, but they don't fundamentally change the core way of interacting with unity afaik.
Is this relevant to a beginner?
no, learn the normal systems first - these will build on that knowledge
ECS is a pretty fundamentally different way of interacting with and thinking about Unity imo.
i haven't used it but have taken a few looks is it different in the way that networking / multiplayer is different for unity?
NullReferenceException: Object reference not set to an instance of an object mouseScript.Update () (at Assets/Scripts/mouseScript.cs:37)
so, i am currently getting this error
care to share the script
A tool for sharing your source code with the world!
As I told you a while back, your spriteRender variable in mouseScript is null because you are never assigning it anywhere, and it's private so it cannot even be assigned in the inspector
Also why did you make your own class/script called spriteRender which is almost certainly causing you extra confusion?
no wait this spriteRender spriterender is the type used in the other script...
ok why is that second one even there
that just looks there to confuse me and you and everyone
no
right but you didn't declared it in the instance nor gave it any reference so it's null
ok sorry, taking a closer look, my guess is you have another copy of the mouseScript script in the scene
so...i made another script and attached it to the box and it contains a ref to the sprite
and you didn't assign the spriteToRender variable in that one
why haha
not this you were correct the first time
oh no you're right
yeah and younever assigned the reference to that other script
cus otherwise, i was referencing sprites in the mousessccript itself
ok well regardless, you need to properly assign this new reference now
wait lemme check
you have named things so confusingly that I think I would probably hurt myself in confusion working on this
oh wait, i need to attach the script on the inspector and for that i need to make it public
what you call "Attach" is actually assigning the reference
i thought scritps referenced other types by themselves like when you use headers and stuff
no...
that'd only be the case for static classes
but when we do using something something, it does that right
using somthing; is completely different heck those arent even classes
you should really consider going through the beginner c# courses pinned in this channel so you can get a proper understanding of the language
c# doesn't use header files. that's just adding a using directive for a namespace so you don't need to fully qualify type names when using them in that scope
that's c++ lol
cpp does have similar using statements but they arent always used
ya...i learned cpp before this that's why...
using in c# is like using namespace in c++
be glad we dont have to deal with headers or forward declaration in c#
i'm just glad i dont have to deal with java in c#
is java that bad? its been soo many years since I last used it
aight, thx for the help guys. ima go do smth else, my neck is killing me
no, it's just different enough to fry all your muscle memory π
tbf that's all the c-syntax languages...
yes it makes me depressed whenever i have to use it in school (my computer science class is in java)
i remember System.out.println and String
not even the worst of it if you make a list, dictionary or anything of the sort you have to use the class names for the base data types so instead of int it's Integer, boolit's boolean. For inheritance it's extends, for interfaces it's implements
oh god I didn't know that about generics/templated types ugh
C# has so many QoL features that java doesn't. java doesn't even let you define your own value types, the only value types are the primitives included with the language.
also no properties, no default parameters, no extension methods, no null coalescing, operator overloading, string interpolation
java has string interpolation now iirc
i never realized how much i loved string interpolation until i was forced to spend a month working with concatenation in java
honestly the extends/implements, despite being more verbose, is a lot clearer in Java. in c# implementing an interface looks pretty much like inheriting a class even though they are different concepts
as for properties, java basically just does the methods directly
generic constraints (extends/super, ?) are actually better in java afaict
last install i did was october and it didn't otherwise idk
yeah, but properties are a nice quality of life feature so you don't need to implement the methods manually. especially auto properties (which got even better in c#14 with the field keyword)
Honestly Dictionary sounds alot user friendly then, i don't know- hashmap on java.
this is also news to me, but tbf i haven't actually used java in like a decade
ok but what did you actually install? it's in java 21 (lts) if im reading this correctly
they are the same thing
Yes but the name makes sense. What does hashmap even stand for?
you also don't need to implement them manually in java. it's a common idiom, so ides can autogenerate them
it's a map that works by hashing, exactly what dictionary is
map is a synonym of dictionary - and in fact, java has an interface Map with several implementations, HashMap, LinkedHashMap, etc, with different features. much more flexible than what c# provides
it's a collection of hashed keys that map to values. Dictionary is actually less clear about what it is, hashmap is a pretty concise actual description of what it does
Oh so the hashmap name derives from a different concept that is linked to it?
map is a synonym of dictionary
map - c++, js, java
dict - c#, python
no, it's the same thing
dictionary just doesn't say it
i meant like the naming convention, hashmap and the map part if you understand those
map and dict are the same thing
hashmap becomes clearer to understand?
Its weird that we have List in many languages but its vector in cpp
the hash part says how it's implemented
fun fact, java has both
also js calls lists arrays
fun times
javascript is fucked anyway
they all are in different ways tbh
lets just go back to having blocks of memory and pretending its an array
well that's pretty cool. I also heard they recently made something like minecraft fully open source. So minecraft modder's could have alot more freedom
none of the languages i know (which tbf isn't a lot in comparison) do generics the same way as each other
(ts, c#, java, c++, py)
oh heavens no, they'd never make a commercial product fully open source
Unless if they plan on abandoning it.
nah, corporations just hate us unfortunately
No they will just stop applying obfuscation to minecraft java so the decomp will recover all naming
oh excuse me. they're just removing obfuscation's, you're right.
it's not open source.
basically all managed languages have this problem, they retain soo much data you can easily decompile stuff
they're just not making it a living nightmare, after what? 15 years?
Yeah, you corrected me before i even looked it up.
They probably realised there is no point because the community name mappings just got updated for new content
so guess they thought "we might as well stop doing this"
just make it open source. Why not be user friendly? It's not like this is windows or anything, it's just a game. and it already has the biggest modding community to date.
Im sure they would rather you only decomp a copy you purchased
commercial product by corporation moment
corporation should be a trigger word.
what would be the most simple way to add camera sway into my game?
to be more specific, whenever the player walks I want the camera to bob up and down.
I personally haven't done this before and I think it would be better to ask instead of starting blind
probably cinemachine noise:
https://discussions.unity.com/t/cinemachine-head-bob-recommended-approach/882075
does anyone know of any repositories I could look at for examples of making a group-based combat system (one enemy attacks at a time, think like batman arkham etc.)? I've been trying to make one for our uni project for like a week straight now and I'm struggling like crazy and getting a bit disheartened
I'm not even sure how to describe it exactly, but an AI system where a bunch of enemies circle or move around the player and take turns attacking, rather than the standard "Walk to player -> attack"
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π 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.
Looks like you check if player is null or npc is null AFTER you use them so:
change this:
bool shouldFaceRight = player.position.x > npc.position.x;
if (player == null || npc == null)
{
return;
}
to this:
if (player == null || npc == null)
{
return;
}
bool shouldFaceRight = player.position.x > npc.position.x;
how did that cause the error
wait is it cuz it runs from top to down
oh wait yea maybe thats why thx
hi another question. i have a bus stop script where the gamemanager puts all the stops into a script then the person picks a random number between how long the list is and 1. is it better if i use a queue as the stops will be most likely one after the other or would a list be fine here?
public static List<GameObject> stops = new List<GameObject>();
public static Queue<GameObject> stopsQueue = new Queue<GameObject>();
out of these 2
cus atm im thinking switching to a queue although a bit of effort and time would be beneficial because i only have to dequeue instead of removing from the list which is easier
Shuffle the list then iterate over the shuffled list
so a queue would not be optimal here?
because i was thinking dequeue each stop then deactivate the stop script
im kinda new to the whole idea of queues so thats why im wondering
Hiya, currently not at my pc and I dont want forget about this
But, does anyone of you know how fix a player stopping their movement when walking into a wall diagonally?
I think I have to use a material
Something Ive forgotten time and time again
It wouldn't really get you anything over a list
Either way you need to shuffle the order
It depends how your player moves
You're thinking of a Physics Material though
Yeah
Can I dm you it once Im back? Cause this message might be long gone tbh
Idk if I can find it
On my phone
From memory im using transformDirection with linearVelocity
