#💻┃code-beginner
1 messages · Page 155 of 1
I would if there is no way to check if those int belong to instanceID or not.
but if there is why not? the game logic doesn't need to know if it belongs to a component or not
You still haven't answered WHERE this list comes from
i still have no clue what are you trying to do
as discussed in this stackexchange thread, Time.time may start becoming inaccurate after a 9-hour playsession
https://gamedev.stackexchange.com/questions/141807/what-happens-when-time-time-gets-very-large-in-unity
if you want to keep a running timer / ticker for whatever reason, is there a recommended way to do it?
some examples:
timer += Time.deltaTime * rate;
while (timer > 1.0f)
timer -= 1.0f;
timer += Time.deltaTime * rate;
timer = timer % 1f;
if(Time.time - startTime > 1f) {
startTime = Time.time;
}
I think the first two give more or less the same end result, while the third one might run into inaccuracies in long play sessions. Thoughts?
and for me it seems that your entire debugging structure is implemented incorrectly
why do you have a list of ints that has instance ids and other things
so you can split it now, since you dont know where the int from and the int can be instance ID (false positive)
and want to separete what is instance id what is not
why not just get system time
the list come from a class?? i don't know what that means.
But the int is sometimes just random int, sometimes from GetInstanceId()
how do you add elements
to that list
just make 2 lists
one for instanceIDs
one for random things
why are you putting everythnig into one list, then trying to figure out what is what wtf
why are you making your job harder 😄
hmm maybe I should show a code? I don't know if it can explain what I'm doing.
// This is a class that handle an action that might be requested by multiple entities.
// It prevent a disabling of an action when only one entity is finished it's request.
[System.Serializable]
public class RequestAction
{
// Triggered when requestList.Count is changed from 0 to 1.
public UnityAction onActivated;
// Triggered when requestList.Count is changed from 1 to 0.
public UnityAction onDeactivated;
// Triggered when requestList.Count is changed between 0 and 1
// true is the same with onActivated, false is the same with onDeactivated
[InfoBox("Please only connect this with code, thank you!")]
[HideInInspector] public UnityEvent<bool> onStatusChanged = new();
[ReadOnly, HideInInspector] public List<int> requesterList = new();
bool currentStatus = false;
public void AddRequest(int requester) {
if (!requesterList.Contains(requester)) {
requesterList.Add(requester);
Refresh();
#if DEBUG
RefreshObjectLists();
#endif
}
}
public void RemoveRequest(int requester) {
if (requesterList.Remove(requester)){
Refresh();
#if DEBUG
RefreshObjectLists();
#endif
}
}
public bool GetStatus() {
return currentStatus;
}
void Refresh() {
if (requesterList.Count > 0) {
if (!currentStatus) {
onActivated?.Invoke();
onStatusChanged.Invoke(true);
currentStatus = true;
}
} else {
if (currentStatus) {
onDeactivated?.Invoke();
onStatusChanged.Invoke(false);
currentStatus = false;
}
}
}
is this your approach?
- you have a list of integers
- some integers are IDs of things and others are not
- you want to check if an integer matches the ID of a thing, and if so, you do an action?
what happens is the integer on the list randomly happens to match an ID, but wasn't an ID, just a randomly matching number?
then the game will still run just fine. probably.
I only need info about wether or not it is instance ID for debugging purpose.
coroutines are also an option, I'm asking if there's a recommended way
there is chance of false positive so you need to split the list, if it doesnt matter then keep your work
then use InstanceIDToObject
id' just sync to system time every so often
foreach (int id in yourList)
{
Object obj = EditorUtility.InstanceIDToObject(id);
if (obj != null)
{
// The integer is a valid InstanceID, and obj is the corresponding object
Debug.Log($"InstanceID {id} belongs to {obj.GetType().Name} component");
}
else
{
// The integer is not a valid InstanceID
Debug.Log($"Integer {id} does not correspond to any InstanceID");
}
}
I did use that. I wrote it in my question.
then what else do you need
@lean basin
if you add cs at the end of the first three backticks you get colour information btw
```cs
some code
```
#💻┃code-beginner message
I need to know if those belongs to MonoBehavior or not.
if(obj is MonoBehaviour)
if it's a class that inherits from MonoBehavior, will it still returned true?
im pretty sure I tried that before and it returned false. Let me try again
public class HelloWorld{
public class A{}
public class B:A{}
public static void Main(string[] args){
B b=new();
Console.WriteLine (b is A);
}
}
try it
there's IsSubclassOf , which might be what you want. is MonoBehaviour might work too, I haven't tried it myself, but a quick google search implied it might not work in all cases
is or as will work, is returns true/false, as return class or null, use either. is is more efficient if you dont actually need the cast
Oh it works!! thanks everyone
My bad, looks like I actually haven't tried that before. Instead of is I used as then compare null. And I mistakenly thought I already used is.
How to force resolution to be the same in the build as in the editor? For example, i have 1440x3088 and when builded it shows all unplayable area of the game, which are out of the camera in the editor.
Get world position of object as a child
Same resolution, or same aspect ratio?
@drowsy totemaspect ratio
Well it should be as in a mobile, but i want it to be that way on PC either
With black bars or whatever
It makes it this way, when i want to constrict view camera to the width of this bottom line
And in the editor the camera set exactly like that
But not in the build
I found a thread discussing this, with a code example from August 203 in the last post
https://forum.unity.com/threads/option-to-enforce-aspect-ratios.1473063/
Basically, they edit the values of the Camera object to enforce a specific aspect ratio
@drowsy totem brilliant. That's why i needed. Thank you
Hello! I need some help. I am making a choose your own adventure game in Unity. Should I use scenes for every new choice?
no
so what should i do?
Some kind of dialogue tree
Look into Ink for example
Or NaniNovel
Well, the problem is that my text adventure game is not quite standard. And plus I've already programmed a choice system.
i would suggest looking into one of these existing systems and seeing if you can adapt your idea to work with them
It's a life simulator that is fully randomized.
I'm just not sure how it would work.
What I'm asking is just, what should I use scenes for, and what I should not use them for.
scenes are, among other things, containers of data that takes a while to load
you make choices quickly, and want the responses to be quick
you don't want to be loading and unloading data all the time, so you shouldn't change the scenes too often
The idea of the game is that it gives you an event in your life, and then you respond by choosing
yes, that is pretty typical for a choose your own adventure game
but it skips a month every turn
it's pretty typical for turn based games to have a turn counter
whether turns are days, months or hours, it's just a number going up
yes, but what should I do for it?
which text game / CYOA tutorials for unity have you watched, or which games in the genre have you analyzed from a technical perspective?
I haven't done any of those in Unity, so I don't know the best practices, but I assume there will be resources out there
Just I don't want to load a scene for every new event
so what should I do? Just change the text?
you'd want to have an event manager
that's separate from your UI
let's say you have an event UI
it shows the typical CYOA stuff - text description, visuals, choices, perhaps some stats and other info
you have a separate set of data that includes each possible event
each event knows its texts, visuals, choices etc
you have some sort of an event manager that reads the info from the chosen event, and uses it to set up the event UI with the correct stuff
Alright.
and when you make a choice, it displays whatever the event needs displayed, and changes the stats and other info as necessary
a scene would be necessary if there's a need to change the UI in a major way
Ok. Thank you!
say, moving between life stages, where the information available and events available need changing
just so you know, there's a bunch of game engines specifically for CYOA games, text adventures and visual novels, and one of those might make your game idea easier to implement than Unity
you can absolutely do it in Unity too, and it can be a good way to learn, so it depends on how much your goal is "make the game", and how much it is "learn new stuff"
Ok, I will note that. Thank you!
how can I perfectly allign to objects in unity
How do you mean?
these two objects arent perfectly alligned
as you can see there is a little gap
I want them to be perfectly alligned
Math, you know their position and their size, so calculate where the edges are and position it like that

As they are rectangular , you can calculate it by using half of the width/height to determine the x/y coordinates
how can i add like a character and movement animation into my game is the only way just making it all myself or is there like a way to just import it
this is a code related channel
Trying to calculate for input duration (how long player has pressed button) , any idea why i get negative numbers? xDir and YDir are fields of the movement class
private void Move()
{
xDir = Input.GetAxis(horizontalAxis);
yDir = Input.GetAxis(verticalAxis);
Vector3 moveDir = new Vector3(xDir, yDir);
transform.Translate(moveDir * movementSpeed * Time.deltaTime);
}
private void CheckInputDuration()
{
if (Input.GetButtonDown(verticalAxis) || Input.GetButtonDown(horizontalAxis))
{
startMoveTime = Time.time;
Debug.Log("Start = " + startMoveTime);
}
if (Input.GetButtonUp(verticalAxis) || Input.GetButtonUp(horizontalAxis))
{
endMoveTime = Time.time;
Debug.Log("End = " + endMoveTime);
}
float time = endMoveTime - startMoveTime;
TimeSpendMoving += time;
Debug.Log("Time moved = " + TimeSpendMoving);
}
this might be simpler with InputSystem, which invokes a method when button is pressed or released
Your logic is wrong here.
also get button up for an axis is wacky
You're starting the timer whenever either the vertical or horizontal axis goes "down"
I guess that'll happen when the axis goes from 0 to non-zero?
Then you stop when either axis goes "up"
and then you're constantly adding endMoveTime - startMoveTime to TimeSpendMoving
which makes no sense; that's adding the duration to the total every frame
this is doing all kinds of wacky things
here's how I would handle this
Vector3 moveDir = new Vector3(xDir, yDir);
bool moveHappening = moveDir.magnitude > 0.01f; // some small value
if (moveHappening) {
timeSpentMoving += Time.deltaTime;
}
if (!currentlyMoving && moveHappening) {
startTime = Time.time;
} else if (currentlyMoving && !moveHappening) {
endTime = Time.time;
float duration = endTime - startTime;
// do something with the duration here
}
currentlyMoving = moveHappening;
this will add to timeSpentMoving every frame that you're moving around
it will also record when you start and stop moving
took a while to wrap my head around it, but now this makes more sense, thanks!
np!
I'm making a fighting game and want the name of the character appear on a textbox when the mouse hovers over them by reading their profile image. here's my script:
code
//public class ChooseLeaderButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[Header("Elements of Faction")]
public TMP_Text chooseText;
[Header("Elements of Leader")]
public Image imageOfLeader;
string nameOfLeader;
string currentLeaderName;
public void OnPointerEnter(PointerEventData eventData)
{
nameOfLeader = imageOfLeader.sprite.name;
currentLeaderName = nameOfLeader.Replace("ChoicePic", "");
chooseText.text = currentLeaderName;
Debug.Log(currentLeaderName);
}
public void OnPointerExit(PointerEventData eventData)
{
chooseText.text = "Choose Your Character";
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
it's a ` not a '
bottom ones as well at the closing side
and u need 3 of them
and a linebreak. u have a comment at the start
public class ChooseLeaderButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[Header("Elements of Faction")]
public TMP_Text chooseText;
[Header("Elements of Leader")]
public Image imageOfLeader;
string nameOfLeader;
string currentLeaderName;
public void OnPointerEnter(PointerEventData eventData)
{
nameOfLeader = imageOfLeader.sprite.name;
currentLeaderName = nameOfLeader.Replace("ChoicePic", "");
chooseText.text = currentLeaderName;
Debug.Log(currentLeaderName);
}
public void OnPointerExit(PointerEventData eventData)
{
chooseText.text = "Choose Your Character";
}
}```
like this?
yes but is ur class commented out on purpose?
no, I just put it wrong
haha okay whats the issue with the code
now
I want the name of the character the player is going to select to appear on a textbox when the mouse hovers over the image/button of the character. the console says I read the name fine but the text in the textbox doesn't change
are you changing the value of a text property of the texxt mesh pro related to the textbox?
textmeshpro
Is it an InputField or just a normal text object?
a normal text object
the textbox just allow the player to read the name to know who they are choosing
Seems like one of two possibilities:
- Something else is changing the text back after this sets it to
currentLeaderName - The text getting changed in code is different than the one you think it is
I think 1 is more likely, it's possible a different object's PointerExit is being run after this object's PointerEnter
And overwriting it back to default text
but wouldn't OnPointExit just change the text to "choose your character"? the text is just empty
Ah, in that case then it's likely either situation 2 or there's another script changing it to blank
How are you assigning chooseText? Is it a prefab, or an object in the scene?
an object in scene
And that object is directly dragged in to each instance of this class?
just found in a different script that the choose text is chooseText.color = textTransparent;
that seems to be my problem
yes
Yeah so it's definitely another script overwriting the text, which it seems like you found
thanks for the help anyway
Ok, I've been able to fix it. Thanks for the help!
Hi. I decided to make a more "realistic" flashlight. I want the flashlight to keep up with the camera's rotation speed. I wrote a line (29) for this. The flashlight lags behind the camera, but it lags too far behind. What else do I need to add?
is the lantern parented to the player?
if so, this code doesn't really make senes; it's going to set the local rotation of the lantern based on this frame's mouse moverment
You should not be multiplying mouse input by deltaTime
anyway - make the light a child of the camera
Script on the Camera
I am watching a coding tutorial and the person uses "snap settings" I can't find any snap setting on my version of unity
does anyone know where to find them?
thanks
Hey, guys! For one reason, when my game is Game Over I still can interact with the pause button. I was thinking how to fix it I have tried everything.
Here is the code:
{
if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == true)
{
if (gameIsOver == false)
{
StartCoroutine(ResumeAfterDelay());
}
else if (gameIsOver == true)
{
gameIsOver = true;
}
}
else if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == false)
{
if (gameIsOver == false)
{
StartCoroutine(PauseAfterDelay());
}
else if (gameIsOver == true)
{
gameIsOver = true;
}
}
}```
when does this code run? What does any of this have to do with your pause button?
I am not sure I just got confused
In this, I have the input for my pause button
also why do:
if (gameIsOver == false) {
...
}
else if (gameIsOver == true) {
}```
You can just do:
```cs
if (gameIsOver) {
}
else {
}```
wdym by pause button? Is it a UI button?
Or are you talking about the escape keyboard button
I don't know I just used to write it like that
yeah that makes no sense lol
You need to explain what this code is supposed to be doing and where/when/how it runs
Log stuff like if pause is active and if game is over
Is this code being called from Update somewhere? From a UI bitton handler?
Anyway, I have a button that enables and disables the pause menu screen which for my game is a gameobject
UI button? #💻┃code-beginner message
I am using escape button
ok so is this code in Update?
yeah
ok so - cs else if (gameIsOver == true) { gameIsOver = true; }
this does absolutely nothing
I don't understand why it's here or what you expect it to do
I have something like this now
if you don't want to be able to pause when the game is over then I would expect something like:
if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive && !gameIsOver)```
{
}
else if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == false)
{
}```
I have to put coroutines inside of them
Don't worry about that I am just capricious
void Update() {
if (gameIsOver) return; // skip everything
if (Input.GetKeyDown(KeyCode.Escape)) {
if (pauseIsActive) {
// unpause
}
else {
// pause
}
}
}``` This is how I'd do it
Here you return something after the first condition what is that your return?
If you can pause and unpause, we can assume game over isn't ever true.
wdym by "what is that your return"?
return means to exit the function immediately
He returns void
yeah ok
since the function has void as the return type, we don't need to return an object. We can just return; on its own
ok
@wintry quarry Hey! So, whenever I want to exit a function completely I have to use return right? I just didn't know what to put on the else statement after the if condition.
Like if I don't want to do something else I can exit with that keyword?
i don't understand what the point of that else statement is in your code. It seems to be "if the game is over". You said you don't want to do ANYTHING in that case, so there's no point to put any code there, right? It would be pointless to put return there because the function is already ending.
So, I can just leave it blank?
why not
Alright!
My recommendation for a simpler code structure overall is here
how do I compare the rotation of 2 objects around only one axis? I tried just comparing their transform.rotation.EulerAngles.y but then when one would snap from 179 to -179 the code breaks
https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html you plug in the two object's forward directions and the axis
so is there a function to compare the angle just around aroudn an axis rather than just total difference if that makes sense
ah ok thans
so for example:
float angle = Vector3.SignedAngle(objectA.forward, objectB.forward, Vector3.up);```
should that minus be an =?
yes
the second is from top - would your code discriminate between the two or would it just return the total angle
because one of the objects' gameObject.forward is pointing down and to the right
comparing camera to the walls of that frame
the vectors will be projected on the plane of the provided axis
and then the angle will be calculated
so it's fine
ah ok awesome
How can I play multiple audio clips from the same object? Right now, I have 2 audio clips that each have their own audio source on an object, but if they play at the same time, it messes up the audio
Use PlayOneShot
Tried that but got this error. Not sure what it means
mauybe look at the documentation for that function
There is of course also https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
There is no overload of PlayOneShot that has no arguments. You need to pass it an argument like your IDE suggests
The argument, would be the name of the audioclip, right?
Check the docs, is there a form that takes in a name as a parameter?
Not sure what I'm doing wrong here
you passed in an audio source
it wants an audio clip
Oh, I see 🤦🏻♂️
Basically you tried to put a CD Player inside your CD Player, instead of the CD
why is nearestPlanet's index in the planets list -1 ? i assigned it as the last planet in the inspector which is element 5, it should not be -1, it should be 5:
https://pastebin.com/bJx0NegZ
also this is the only script with a reference to nearestPlanet.
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.
when I do objectName.forward, they all share what feels like the same forward axis
assigned via Vector3 angleDiff = wallGrandParent.forward - transform.forward;
and turned off via if (angleDiff.z > 0)
FindIndex returns -1 if the find is unsuccessful
I don't undertsand what wallGrandParent.forward - transform.forward would be calculating
Click on an object and look at the transform gizmo (make sure it's set to local). The blue arrow is "forward"
the offset between the angle of wallGrandParent and the camera's transform
what?
What are you trying to do exactly?
Why didn't you try the SignedAngle approach I recommended before?
||Because they didn't understand it and didn't want to learn anything new||
subtracting direction vectors isn't going to give you anything particularly useful
bozo moment, Vector3 angleDiff = Vector3.SignedAngle(wallGrandParent.forward, transform.forward, Vector3.up); triggers an error 'cannot implicitly convert from float to Vector3`
When using PlayOneShot(), I only have to have 1 AudioSource, right? Or do I need one for each clip?
because you're trying to assign to a Vector3 variable inexplicably
Why not follow my example instead?
oh I'm a bozo
You can play multiple clips at once with PlayOneShot
if you just want to know if the objects are facing roughly the same direciton on the y axis you could do this:
// project both vectors on the x/z plane:
Vector3 objectForward = Vector3.ProjectOnPlane(wallGrandParent.forward, Vector3.up);
Vector3 camForward = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
float angle = Vector3.Angle(objectFoward, camForward);
if (angle < 90) {
// they're facing sorta the same way
}
else {
// they're facing sorta opposite ways
}```
However, if you change the audio source's pitch, the pitch of all of the playing clips will change, iirc
The audio source is where the sound comes from, if they all come from the same place that's fine
Yeah, but do I need an audiosource attached to my object?
Ahh okay
Yes.
If you don't want to have an audio source at all, there is https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
since u are making a 2d game u should just have one audiomanager object and handle all the audio on that. instead of placing audiosources on your objects.
Hmmm, I hadn't thought about that. That could be a good idea, thanks
is there a way to make it so th Ai monster keep facing the direction theyre going?
like, without going off the trail/cutting sharp edges
Idk if you'd even want to touch this, but FMOD is fantastic for audio handling if you want to get a bit more in depth into dealing with audio. However, it is a bit of a learning curve. Personally, I like it better than the standard Unity way of calling audio; but everyone differs
It would depend on context but surely it's possible.
this is the default way a NavMeshAgent behaves
i made this for examplifying, the blue is what i want it to do and red is what its doing
It's doing exactly what you told it to
maybe you want a grid-based pathfinding instead of navmesh
It's finding a path towards the destination inside the navmesh
yes, if you want the entity to move on a grid, you need to make it move on a grid
So, I've tried making an audiomanager object that has an audiosource attached to it. But now when I play, I get this error and no sound
This is my code. Am I doing something wrong?
well, where's the error coming from?
i disabled this and im going to test if it works
it's absolutely not coming from the line you have highlighted in the code editor
this has nothing to do with your problem
damm
OffMeshLinks are explicitly placed to create a "bridge" across an otherwise unwalkable gap
Can you show the entire error from the console window?
Also, post the !code more appropriately so we can see the line numbers
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you are passing null into the method
I'm not sure I know what you mean
the parameter you passed in
was null
Did you assign your audio clips?
it seems loike you didn't
Here on the right
what object do you have selected there?
It's that weird error, the AudioSource is null, not the clip
Deep down it calls an extern static method with the source and the clip, and the error says that source is null
So should I put an audioclip in the audiosource?
No you should make sure what you call PlayOneShot(clip) on is properly referenced in your Inspector
Debug.Log($"{name} played the one shot: '{GunShotReloadSound}'", this);```
All the properties here in your inspector are in bold, and show a blue margin on the left. This means the change hasn't been applied to the original prefab.
Any instantiations of the prefab won't have the source referenced
Click the log message and make sure everything is appropriately referenced in the inspector.
The object should become highlighted yellow when the message is selected.
if I double click the error, it does this
Place this before that line and verify that everything is properly referenced
Also log AudioManager just to be sure
This is what I get
Which object was highlighted yellow? Was the fields properly set in the inspector?
when I do that it still takes vertical rotation into account
If I click on the white error, it highlights the object I want to play my audio from
This would be at runtime as you're assigning it in Start.
Show us the inspector for that object when the error occurs
I believe we ran into this somewhat recently, since PlayOneShot is an extension method rather than actually on AudioSource, it gives the "null parameter" error instead of a normal NullReferenceException. Log AudioManager as well
It looks like my Audio Manager reference on the right was set to none when I start the game
but in editing mode, It's set as my audio manager
Probably because you have code that sets it to null
Get component in Start needs to be removed
I need to remove get component from start?
It worked but now if I shoot, I get this really horrible sound. It's meant to be a gun shot, then a reload sound
Does this object have an AudioSource component on it? If not, GetComponent returns null
LOUD SOUND WARNING
Meaning you set AudioManager to null
No, it doesn't
ahh okay
Should I add a script to the AudioManager with GetComponent?
Why
I am completely new to coding trying to make an FPS and currently completely copying code from yt, but when i go into unity i get an error, does anyone know what i did wrong?
woah so many people
You're shooting non stop every 20 milliseconds for one second per fire.
what error
send the error
How do you know that??
you need to configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
you see these functions?
Configure your !ide so you don't make basic syntax mistakes
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
add semicolon at the end of them
From your code - the coroutine
#💻┃code-beginner message
The 2 numbers (24, 24) show what line your error is on
ohh ty
it should look like this
Ooh my gosh, you're right
Thank you haha
how tho, do i reinstall vs
im not getting any errors rn
Read the bot message
Follow the guide and tell us where you get stuck. Ideally, you wouldn't reinstall but run the launcher and ensure the work loads and whatnot are correct.
Running the installer again will not reinstall but rather modify the current installation
Tools > Get Tools and Features >
-
select unity
-
click modify in bottom right to install..
-
in unity go to Edit > Preferences > External Tools and Select it
-
Remember that Restarts can help edge the computer along.. if things dont show up / missing
Is there a way to freeze the player? I want the player to freeze when dying, right now if the player is moving and dies, the player loses control but keeps moving in the direction they were moving in
disable the scripts that make it move
Ooooooh good idea!
if its a rigidbody may have to zero out its velocity and then disable
I installed Cinematic Studio Unity and I can't add a sequence to the project. It just isn't there
How would I zero its velocity?
My movement script is called PlayerMovement. I tried doing PlayerMovement.enabled = false , but it didn't work for me. So I'm trying gameObject.GetComponent<PlayerMovement>().enabled= false;
PlayerMovement is a class.
PlayerMovement.enabled is trying to find a static member of the class named enabled
No such member exists, so you get an error
enabled is stored on specific instances of PlayerMovement
Which is why this is legal code.
you ask Unity to find a PlayerMovement on your game object
show code
then you set the enabled field to false
This will cause an error if GetComponent<PlayerMovement>() can't find a PlayerMovement, however.
So if I understand correctly, to do PlayerMovement.enabled = false, I'd have to reference it first?
You'd need to have a reference to a specific PlayerMovement
if (ArrayDict.wallList.Count > 0) {
foreach (GameObject wall in ArrayDict.wallList)//wall holder parent - BlankNSEW - Check if it is within 180deg FOV of camera's rotation and if not don't render
{
Renderer wallRen = wall.GetComponent<Renderer>();
Transform wallGrandParent = wall.transform.parent.transform.parent;
float angleDiff = Vector3.SignedAngle(wallGrandParent.forward, transform.forward, Vector3.up);
if (angleDiff > 0)
{
wallRen.enabled = false;
}
else
{
wallRen.enabled = true;
}
}
}```
[SerializeField] PlayerMovement playerMovement; // assign it in the inspector
void Whatever() {
playerMovement.enabled = false;
}
This is the ideal method.
Drag an object with PlayerMovement on it into the "Player Movement" field in the inspector
This will assign a reference to that specific PlayerMovement component
Right
Is there any reason why this way would be more ideal than the way I did it?
starting with the weakest reason: there's a performance benefit
GetComponent has to search the game object for a component of the type you ask for
this isn't trivial because you can ask for parent types
so GetComponent<Component>() will find some component
secondly: it makes your code easier to read
playerMovement.enabled = false; vs. GetComponent<PlayerMovement>().enabled = false
thirdly: it's more flexible. Your PlayerMovement component doesn't have to live on the same game object. you might wind up moving things around later.
I do still use GetComponent whenever I know the component has to live on the same object anyway
but I don't do it that often
and if I do, I do that in Awake, once
yup, like Fen said.. u dont try to disable the Script.. u have to have a reference to that script and disable that
PlayerMovement.enabled = false; is trying to set a field on the class itself
which would work if enabled was static
but it's not!
PlayerMovement myPlayerMovementReference;
myPlayerMovementReference = GetComponent<PlayerMovement>();
myPlayerMovementReference.enabled = false;
altho if u had public PlayerMovement myPlayerMovementReference; you could just assign it via hte inspector
but still.. dont try to disable the Script, instead disable a reference of an instance of that script
in case you are unclear about why I used [SerializeField] and spawncamp used public
serialized fields appear in the inspector.
by default, public fields get serialized, and non-public fields do not
you can use [SerializeField] to tell Unity you want to serialize a non-public field
its b/c im a prototyper and i use publics way way too much
For anything that's only going to be used by the class itself, private is the ideal access modifier
What's the difference between public and [SerializeField] ? I've mostly been using public whenever I want to assign something in the inspector
It also happens to be the default.
public means u can access it from any script
if u use serialized private.. you can still see in the inspector..
A public member is visible to every class.
but with SerializeField, you cant?
BUT other scripts wont be able to access it
A private member is only visible to the declaring class.
Oooooh
if its a private SerializedField
(or struct. i forget the proper name for "class or struct")
The type or member can be accessed only by code in the same class or struct
Ah. There is none!
If you're just starting out, don't sweat it too much.
private serialized are good for stuff like you want to do..
you really need a reference to the script ur working in.. but you dont necessarily need it public for everything..
so just drop in teh reference in the inspector.. and u dont need to use any getcomponenet calls or anything
Access modifiers are nice to get right when you're writing code for just yourself, since it's easier to reason about your code when there are fewer ways for A to mess with B
They're vital if you're writing code that other people use. Once people depend on some non-private member, changing it can break their code.
Note that "other people" includes "you from six months ago"
dear Fen: what the hell were you thinking
Wait, but the script that I'm disabling is the same script I'm writing the disable code into, so would I still have to do the same process?
Because I'm not disabling a different script
its fine.. but think about what u want
Access moddifiers are irrelevant here
The access modifier on the field affects who can see the field
unless u enable it from another script
public class Foo {
[SerializeField] private Bar bar;
}
only Foo can see that bar field
That's fine, I'm disabling it when the player dies anyway. Then it gets reenabled when the player respawns
public class Bar : MonoBehaviour {
public void Huh(Foo foo) {
foo.bar = this; // compile error
}
}
Huh?
clarifying what the access modifier means
i know.. bad joke. my drumset player wasn't around to do the "badum tiss"
oh, I thought that might be the case :p
hes fired
okay, imma call today "Progress Monday"
and let it wash across my project.. maybe something productive will happen
I think imma work on my pathfinding stuff.. I want to click and hold on a unit.. then this allows me to draw on the ground.. as I draw waypoints will be generated every X amount of movement..
when i release the waypoints all get added into the navigation setup
THEN idk.. b/c the navmesh agent is gonna ignore the lines i drew
the only thing i can think of to compensate is to add many waypoints... but then the movement will probably look unnatural.
hey, so I have a problem with the RigidBody2D physics system when I want to slide right when I hit the ground, the horizontal velocity that I am setting isn't very consistent depending on the angle of which I am hitting. Here I drew a picture to show you what I mean:
What I want to to have a consistent speed when sliding and hitting the ground no matter what way the player does it. So how do I fix this?
is there a random float generator instead of int?
Random.Range will produce floats if you give it floats.
why isnt this working?
OHH
but there's something at the end of the first line..
someone should start a freelance "second eyes" type service
It's not a syntax error, but it is semantically bogus here
two of my favorite words, "semantically" and "bogus", right in a row!
why would the error not come by the semicolon?
why would it let me do it if it was abstract or extern
It's valid to write a method without a body in some contexts.
like if the method is abstract
An abstract method can only be declared inside an abstract class.
Any non-abstract class that inherits from the abstract class must override the method.
In that case, the abstract method must be declared without a body
You also do this inside of an interface
iirc every method in an interface is implicitly abstract
(or something close to that)
That's why the error wasn't on the semicolon. It's not really the semicolon that's wrong here
What's wrong is that your non-abstract method doesn't declare a body
(also, an extern method is one that's actually defined somewhere else. I haven't used that keyword in C# yet)
why is it still spawning things after one spawns?
What does SpawnDelay do
So, let's work through this line by line.
You start, transform.childCount is presumably 0, and playerSpawned is false.
This means the first if statement occurs and playerSpawned is set to true, and the coroutine is started.
The coroutine reaches a pause.
End of fixed update.
Next fixed update, transform.childCount is still 0, and playerSpawned is true.
This does not satisfy the if condition, so we move to the else block.
playerSpawned is set to false.
End of fixed update.
Next fixed update, transform.childCount is still 0, and playerSpawned is false.
This means the first if statement occurs and playerSpawned is set to true, and the coroutine is started.
The coroutine reaches a pause.
End of fixed update.
Repeat the above blocks until the first coroutine's timer is up, and transform.childCount becomes 1. All other coroutines who have started since then are still running, and will spawn another object
Guys. I'm don't understand why raycast don't work there. This function calls from above and should return collider of selected object
the only method i know of that helps is using debugging tools and breakpoints to step thru the code
but its return null
or just walking thru it like digiholic just did
this
ya need colliders rather wrong raycast type
you're trying to use 2D raycast with a MeshCollider
MeshCollider is a 3D collider
Make sure you only use 2D colliders with 2D physics queries
while we're here.. this override thing doesn't have to be assigned does it? like include layers say Nothing.. but it'll still work like it should w/o having those selected eh?
like box collider 2d?
sure that's one of the 2D colliders
any 2D collider
thank you, very well explained
thanks wm!
also for spheres/circles you can just use primitive colliders
primitive colliders are cheap.. i try to use em as often as possible..
Hi my code works, i can pause the player at any moment and the animation pauses and then restarts where it left of. My player also does not move while im attacking. But im a bit unsure if im over complication the code. https://gdl.space/yuvesohuza.cs does it seem a bit hacky?
as long as its working dorry worry too much, refactoring comes later if at all
cool thanks just worried about the two returns in the update
nothing wrong with having return in Update, pretty normal
cool thanks for your advice
I occasionally footgun myself with that
it goes like this
- code that always runs
- code that only runs sometimes
I decide an early-return between the two makes sense
Then I forget that I did that and add some more code at the end!
lol
e.g. I have a "helpless" flag on entities that get set when they're unable to act; I exited Update early in that case
yes i can understand why
then I forgot I did that...
i just created a bool in my game manager for pause. then i set it in my menu to toggle on and off. then i did the same in another class and wondered why it dont work. its cuz i set it false some where else. So now going to add two functions in my game menu and just add every thing that needs to be paused there and call the meathod instead
could make an Interface for each object that needs to like pause, then listen for event
IPausable or something
ohhh dont no about listen events is that easy to set up
events are quite powerful and pretty easy to get into imo
https://learn.unity.com/tutorial/events-uh
edit: this one good too
https://gamedevbeginner.com/events-and-delegates-in-unity/
thanks ill take a look
Unity Events are awesome..
if(condition) -> InvokeEvent
then u can pretty much do anything within the event
yh think ill do that route
def eleminites a lot of polling for stuff in Update
i wrote my own event system..
uses an Action class
i drop it on my gameobject and its set up to do different functions
like trigger it when the gameobject spawns in, or an option for a delay, or mouse click
just some generic stuff.. then i have others with a list of actions and i can just stack em in there.. and it'll loop thru the actions invoking them 👍 pretty neat setup
That sounds amazing.
Does it end up making you think what else can i add to it, when it prob doesnt need it
public class Action : MonoBehaviour
{
[Tooltip("Uses Start Method When False")]
public bool onEnable;
public UnityEvent ActionEvent;
private void Start()
{
if(!onEnable)
{
ActionEvent.Invoke();
}
}
private void OnEnable()
{
if(onEnable)
{
ActionEvent.Invoke();
}
}
}
lol.. yea i have that problem anyway
lol think ill end up doing that too
i have trouble knowing when enough is enough
its so easy to fixate on a certain system or mechanic and build it more elaborate than u actually need
i usually just package it up at that point.. and have a package i can pull in and modify the things i dont need
Yh so i was also fixated on statemachine and i ended up adding to somthing that prob dont need it. i saw i had it on my player and thought why not. Think thats when things get over complicated
ya, nothing wrong with it tho.. if ur a beginner and you're learning its great to experiment
yh thats it
even if u dont end up using it, atleast u went thru it, learned some stuff and exposed urself to new things
lol
welp 🍀 with w/e ur doing
test.cs(26,13): error CS0103: The name 'ChangeTexture' does not exist in the current context
I've been trying for a few days and I can't
I don't know why I get that error that this objective does not exist
How coud I check for a high concentration of a certain type of object in screen?, like, a proyectile that automatically search for a high concentration of enemies to maximize damage
What is ChangeTexture
to change texture to another texture, right?
Show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its actually a material change if i remember ur issue correctly
Some sort of renderer . material = new material
the error seems to imply you dont have a function called that..
go ahead and share ur script ^
ok
ChangeTexture or ChangeMaterial which is more likely what u want... are not built in functions or anything.. ud have to create the method and then call it
is ondestroy called before or after destruction?
I want a function that will output a bool if my camera is in front or if it is behind the wall - I've been messing around with Vector3.SignedAngles for a few hours but either my math is terrible or it's the wrong way of approaching the problem
and I'm pretty sure wallGrandParent.forward is the wrong variable to be using because all walls output the same thing for it regardless of their rotation
You should make one (a separate class) for trigger and collision events. Much easier than having the same events in multiple classes . . .
(all 4 walls being logged there are facing a different cardinal direction)
I have found that when I do Vector3.SignedAngles(wallGrandParent.forward, transform.forward, Vector3.up, I do get an angle but then all walls read the exact same angle offset from the camera
thanks, its still a WIP, thats a good addition 👍
Click on the walls in the scene
look at the blue arrow in the scene view
which way is it facing
if they;re all facing the same way this is entirely the wrong approach
(make sure tool handle rotation is set to local)
I have an example. I will share when I get home . . .
there are no arrows
nvm they're facing up
Wdym
I was in game view
yes they're facing up which matches this log
The blue arrow is transform.forward
ah, green is facing inwards which is up, would wallGrandParent.up work?
it's still reading 90 degrees
nvm reassigned it later
public class test : MonoBehaviour
{
private Vector3 lastPosition;
private Material mat;
private Material mat2;
void Start()
{
lastPosition = transform.position;
}
void Update()
{
// Get the current position
Vector3 currentPosition = transform.position;
// Check if the position has changed
if (currentPosition != lastPosition)
{
// Object is moving, change texture to movingMaterial
mat = new Material(imagen1);
}
else
{
// Object is not moving, change texture to idleMaterial
mat2 = new Material(imagen2);
}
// Update lastPosition for the next frame
lastPosition = currentPosition;
not if I'm doing it right
it's randomly switching from (-) to (+) when passing in front
that'd be cool, thanks
foreach (GameObject wall in ArrayDict.wallList)//wall holder parent - BlankNSEW - Check if it is within 180deg FOV of camera's rotation and if not don't render
{
Renderer wallRen = wall.GetComponent<Renderer>();
Transform wallGrandParent = wall.transform.parent.transform.parent;
float angleDiff = Vector3.SignedAngle(wallGrandParent.up, transform.forward, Vector3.up);
Debug.Log($"{wallGrandParent.up}, {transform.forward}, {angleDiff}, {Vector3.up}");
if (angleDiff > 0)
{
wallRen.enabled = false;
}
else
{
wallRen.enabled = true;
}
}```
// Object is moving, change texture to movingMaterial
mat = new Material(imagen1);
what is this? theres nothing in your code called imagen1
and besides that.. i thought you wanted to change the texture/material of something.. in ur code ur just setting materials. you're not using them anywhere
why not build ur materials like u need them.. and just swap the entire material?
offset it by -90 degrees - it works!
I love Quaternion.AngleAxis
It wasn't to select the texture in the textures folder, right?
sorry it was my mistake
then i should delete image1 and image2
I think first thing's first you should probably check the intro to C# guide in the pins and learn how code works. You can't just use a variable or function that doesn't exist, you have to define it
i think the easiest solution for yours is to just make the materials you need w/ the textures already assigned
instead of trying to copy the material, set the texture, re-assign it, etc
public class MaterialChanger : MonoBehaviour
{
[SerializeField] private Material idleMaterial; // assigned in my inspector
[SerializeField] private Material movingMaterial; // same
[SerializeField] private MeshRenderer thisRenderer; // assigned in my inspector
public bool flipMaterial; // public bool for testing
void Update()
{
if(flipMaterial)
{
thisRenderer.material = idleMaterial;
}
else
{
thisRenderer.material = movingMaterial;
}
}
}
``` Sample Script, The MeshRenderer is assigned b/c thats what Renderers the material *on* the cube..
all I'm doing here is swapping the material it uses with the test boolean
same kind of thing can be done with every kind of renderer
The ternary alternative would becs thisRenderer.material = flipMaterial ? idleMaterial : movingMaterial;
where did I go wrong? I created a gameObject called Sword and assigned my inactive gameObject onto it, and made this:
void Attack()
{
if (Input.GetButtonDown("Fire3"))
{
Sword.SetActive(true);
}
}
But when I press leftshift it isnt activating
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
But also, where do you call Attack and is left shift bound to Fire3?
oh... sorry, it was all a misunderstanding.
I am looking for a solution is when I move an image on the screen but the texture changes when the image moves and when I stop moving the normal texture returns 😓
attack is called in update, and yes, left shift is assigned
Show the full script
Anyway, I appreciate that you know something but I will try to continue looking for the method
add Debug.Log statements inside the Attack function, inside and ooutside the if statement
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how do I change size via code?
Lies
You aren't calling attack anywhere
what kind of Renderer are you using?
i understand what ur trying to do .. but the same thing applies to textures..
[SerializeField] private Texture grassTexture; // assigned in my inspector
[SerializeField] private Texture dirtTexture; // same
[SerializeField] private MeshRenderer thisRenderer; // assigned in my inspector
public bool flipMaterial; // public bool for testing
void Update()
{
if(flipMaterial)
{
Material materialCopy = thisRenderer.material;
materialCopy.mainTexture = grassTexture;
thisRenderer.material = materialCopy;
}
else
{
Material materialCopy = thisRenderer.material;
materialCopy.mainTexture = dirtTexture;
thisRenderer.material = materialCopy;
}
}```
like here, you have to copy the material, Change its texture, and then use the COPY
im so stupid
same mechanic, changing textures instead of the material
it just matters what kind of renderer you're using and how the texture works w/ that renderer
I use with UI/Image, Unity 3d
thats even simpler then.. you just have to access the Image component and change the sprite
image doesn't use a texture
well it does use a TextureImage
hmm, ok!
it is working now, I was just stupid, but another question.
The sword gameObject is a child object of the player object, and I made it so everytime the player touches the wall he goes back a scene, metroidvania style. However, the sword hitbox is triggering that, how do I stop it from doing that?
Don't worry, if you don't get it, nothing happens 😅
Do you want the sword GameObject to not be able to trigger the change of scene?
yeah(there is the lowercase and caps version and I always make this confuision)
i think it's .sprite
Either you can user the layer matrix to make them not interactable https://docs.unity3d.com/Manual/LayerBasedCollision.html
is there something wrong with my code ? i dont get why is it not working ?
You have a function in your function
what does it say when you mouseover the squiggly line stuff telling you that you might have problems?
oncollisionenter or collision collision ?
Possible through code as well: https://docs.unity3d.com/ScriptReference/Physics.IgnoreLayerCollision.html
Or make the individual colliders ignore each other: https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
could you please elaborate
You have a function inside of another function
try both!
they're there to help guide you
void Update()
...
void OnCollisionEnter()
...```
Don't put the method inside the other method.
you just have to assign the sprites.
```cs
[SerializeField] private Image thisImageComponent;
[SerializeField] private Sprite sprite1;
[SerializeField] private Sprite sprite2;
public bool changeSprite;
void Update()
{
if(changeSprite)
{
thisImageComponent.sprite = sprite1;
}
else
{
thisImageComponent.sprite = sprite2;
}
}```
wow
yea, it also has a .mainTexture which confused me for a bit
but if its an Image component you're probably most likely using sprites
why doesnt this work? i switched it from if component != null to if trygetcomponent and it doesnt work now
i used this one but still nothing
those dont go inside the update loop
new functions go outside the update or any other loop
All those red curly braces
You have a function in your function
oh yeah i got it thank you just look at the new ss if you may
In the first code it tells me that there is no private -> image but I have created a component and it does not work, what could it be?
an add on
you have to assign it..
you just told the code there is an image component
you never told it which one it is
ah
thank you very much for your help and patience SPG
if its on teh same gameobject as the image component you can assign it in code,
like in the Awake() or Start() method..
thisImageComponent = GetComponent<Image>();
but since we used SerializedField (it exposes it in the inspector) so u can just drag it in
Does try get component not work for this?
if it were private.. (and you couldnt see it in the inspector) you'd have to assign it in code
the code within the tryget will only run if it successfully gets the component ur trying to get
the AI isnt working and its giving me these errors but in the code theres none and the enemy has a nav
Looks like it's not being called on an Active Agent that has been placed on a NavMesh
either:
- the component doesn't exist
- you're looking in the wrong place
wdym?
I mean the thing this code is running on either:
A) Is not an Active Agent
B) Is not on a NavMesh
why is the navmesh surface on the dog?
Okay, is mazeDog an active agent that has been placed on a NavMesh
and it gets called right here on the code
it isnt
then what does this mean?
i mean the navmash lol
The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?
I'm going to review little by little although I don't speak English very well and I use a translator 😖
yes, I understand that you meant the navmesh
but having the navmesh on the mazeDog makes no sense
why's that?
did you read the documentation for what you're using at all
How is the dog going to navigate on itself
i think we have a misunderstanding
the mash and the dog
Okay. The navmesh is not on the dog.
Yeah probably. You've given two directly contradictory statements as to whether the NavMesh is on this object or not
You kept saying the navmesh was on the dog.
you have to add the .UI using statement to be able to access the UI stuff in script
OMG IM SRRY I MEANT THE AGENT :((
well yet u guys know whats happening??
he simply doenst move
I was just going to do that, lol
the code gives it a destination but still
did you setup the NavMesh as well?
It looks like there's a valid NavMeshSurface in this screenshot.
like baking the area?
Is the agent actually on the navmesh? And not hovering above it?
are the dog and the surface for the same agent type?
And are you sure you're referencing a NavMeshAgent in the scene and not a prefab?
shoot this could be it
agents will try to automatically place themself on the navmesh, i dont think this would be the case
unless its realy far away
Unless a collider or some code is keeping it off the mesh
it wasnt
🤔 interesting
no reason to believe that
As in "it wasn't the issue" or "it wasn't on the navmesh"
the issue
we can't assume much in here.. theres some crazy things people do
have to ask all the questions sometimes
Was the error resolved?
screenshot the agent and its inspector
and screenshot the navmesh and its inspector
Okay, so next is to make sure the agent you're referencing is the one you think you're referencing. While the game is running, check the object giving errors and click on the reference to the agent, does it highlight an object in the scene?
how do i get an object to rotate without changing its x or y position?
Rotation shouldn't have an effect on position
Rotating an object doesn't do that in the first place, so, just rotate it
Maybe you've got some other things you ought to share with us
i currently have a player that uses tank controls and he either rotates across his front, or rotates just slightly off enough to be anoying
sounds like your origin is bad
yup, may need to fix up the origin, if its a model u can change it in a 3d software
Wow, it works perfectly, now I will try the motion detector when I keep the image moving. I don't know if that code was "lastposition" 😁
If my player model is that cube, rotating the player will make the cube move around
a bandaid fix is to use an empty container and position the tank where the center should be and rotate that instead
(this cube is parented to an empty object)
i honestly agree there bc the closest i could get to a fix with origin was left center causing the slight position change
i tried that but the objects kept separating
thats the thing the error says the command on the code can only be called on a agent in a navMash
if its physics based it probably would.. ya
wich by all means seems to be what mine is
but if u use an empty container u move all ur rigidbody and stuff to the empty
okay, but did you do what digi asked you to do?
click on the error. see what object gets highlighted in the hierarchy.
Im honestly not quite certain how to do it such that they wont separate when the empty objects collider hits another object
none, it opens the code
click once.
We have confirmed you have a navmesh agent that is on a navmesh surface. We have not confirmed if that is the one your script is referencing.
nothing
it does, wait a sec
will this work for a 2d game?
I have another question, so if I use with (lastposition) to detect motion and change the texture, is there something wrong with that system?
the model is exported from blender, could i have exported it wrong or smth??
all objects work as objects so i dont think thats it
Okay, and if you click on that object assigned to Ai while the game is running, does it highlight the one you think it is?
hmm, it looks like that error doesn't include context
That doesn't seem to be related to your problem
I triggered it and the console didn't take me anywhere
yep
I think Digi suggested selecting the object and checking the referenced field.
Ah, you are right. My bad.
the thing is i had the same code on a different monster and it worked just fine (the monster is disabled so it couldnt be interferring)
if its a 2d game its using sprites.. im pretty sure unity can set the pivot of sprites w/o any special assets
On the line before one of the ones throwing the error, add this line:
Debug.Log($"{gameObject.name}'s ai agent is: {ai.gameObject.name}", this);
This will have the names in the log, and will highlight an object when you click on it (single click), since the error does not.
yeah, the closest setting still doesnt work
every frame that goes by you check ur last position first..
then you check your current position.. (if these match you're not moving) (if they don't match you have moved, so you are moving)
then after all that you set the last position to be this new position where you are now..
that way when you go to the next frame it has the lastPosition ready for you to compare again
😭
Okay, when you click on it, does it highlight the one in the scene we've been looking at?
yes
Hm... so it seems like this is the correct object, and it seems to be on a NavMesh...
Are static variables allowed to be serialized to JSON?
transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z + (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10)); just to check, there isnt anything wrong with the actual rotation code right?
If you clear the console while the game is running, do the errors come back? Or are they one-and-done?
This would imply that the script is on the maze dog object but what about the reference?
I'm going to try it and if not, nothing happens although I would like to know in the future.👍
Yeah, I just wanted to see if the issue might have been that it didn't start on the mesh but then moved onto it after the game started
We checked that one earlier, it checks out
Maybe have it highlight the ai instead
I guess it doesn't hurt to try.
@deft siren , in the log I had you add, replace the ,this at the end with ,ai and then click the log as before.
Let's see if it is possible to detect it .detectCollisions
wow
did you check this as well? #💻┃code-beginner message
checks out as well
no
gimme a minute
it helps me a lot 😄
i try to test everything that i help people with, so i know for sure it works
yeah i dont thing i got what u want me to do
Wow, you are an amazing person who helps people a lot, keep it up and don't give up😄
show the inspector for the surface and for the agent
So what exactly is the code to detect when it moves?😮
one of the surfaces
dog
the surface isnt here
But I have a question, is it possible with the image?
I have an image that moves
it has a transform doesn't it?
what would the surface be then
i guessed you meant the floor
a nav mesh surface
like this?
yes
So I have a game with essentially a ton of very small events in which different things have to happen. Delegates would work well for these events, but aren’t really necessary. I can do individual work around for each one, but they would be pretty random and inconsistent case to case. Is using a ton of delegates better for consistency or should I do the smaller workarounds? I know someone mentioned that delegates create garbage and orphaned subscriptions. What’s an orphaned subscription and what can I do about it?
I asked something similar to this yesterday but I had to go before I could finish asking all my questions
@eternal needle
this
if the transform.position is different on this frame, then it was on the last frame -> you have moved (are moving)
if the transform.position is the same on this frame as it was last frame, then -> you are not moving
- In the script's Start method, create a variable to store the previous position. This variable will be used to compare with the current position in each frame.
_previousPosition = transform.position;(a vector3) or (vector2 for 2d) - In the Update method, compare the current position with the previous position to check if the object has moved.
if(transform.position == _previousPosition){// you havent moved}else{// you have moved}; - set the new position as the previousPosition, so when the new frame happens it can compare again
_previousPosition = transform.position;
i dont have anything like this
but the other monster still worked
you have a surface, as shown by the blue floor thing here. Unless that is your actual floor.
But i suspect you never made one for the dog so it has no surface to walk on
you need to bake a surface for each agent type
i strongly believe i already did that
You said you dont have any nav mesh surfaces, so i doubt you have
show me the surface then
My thinking is that small delegates would be easier when adding things in the future, and would remove the risk of the workarounds not working when I add the new things
still none
I'm not sure how noticeable it is in the pictures but the camera movement when rotating is the current issue that im having 😅
i dont get how you claim you baked a surface for each agent type but you dont have a nav mesh surface. just make a nav mesh surface and this should be done then
its not something (i have a slightly older version but dont think thats it)
hm your navigation tab also does look quite different to mine, i dont have the Bake and Object tag 🤔 am i behind
Oka, I'll try to see how I get it, by the way I don't think I can ask for more help since it's a lot, although I'm still learning thanks to you for teaching me🥲
then you should bake it like the old version..
Open up Window > AI > Navigation
oh, that would explain the difference there. I didnt use navmesh for that version
on ur surface mark it as Static and then in the Navigation window you just opened Bake it
yeah thats the thing i already did that
yeah its all just like that
🤔 interesting
it was even moving a long time before but still with a shit ton of bugs
i really dont get why thats happening cause the old monster still works just fine 😭
ok so i figured something rlly interesting
changed back to the old agent type, humanoid
now its moving but all buggy like i said
gonna try to unbug this
Seems like this got lost
i cant answer some of that but i do know what orphaned subscriptions are..
so you know how u subscribe to something? and then when that something happens the thing knows about it?
well you are supposed to unsubscribe to that thing if u disabled/destroyed the component or w/e
the orphaned thing means you destroyed the thing without unsubscribing..
not sure what happens after that.. like when the event fires off..
Here are some potential issues:
Null Reference Exception:
If the event is fired after the object has been destroyed, attempting to invoke the event on a null reference (destroyed object) will result in a NullReferenceException.
Memory Leak:
The destroyed object, along with its associated event handler, will not be garbage collected as long as the delegate still holds a reference to it. This can lead to a memory leak.
To avoid these issues, it's good practice to always unsubscribe from events when the object is being destroyed. You can do this in the object's OnDestroy method or in a method explicitly designed for cleanup.``` this is what Chatgpt says about it.
ok this one not much of a problem but, the dog is walking backwards, how do i make the navmesh know where the front is at
rotate the graphics so it facing the right direction
ur graphics shouldn't be linked to ur main object anyway
the dog is walking backwards
how do u know its backwards?
probably because the graphics look backwards.. thats the (graphics) im talkin about..
they should be a child of the navmesh.. u should be able to rotate them a full 180 degree's to make the dogs face, his butt
like, the objects?
and his butt, become his face
yeah i tried doing this
it... still walks backwards
rotating the graphics shouldnt change the way the navmesh walks..
the Purple is the Z axis (forward) its the Pawn (the navmesh) fowards direction
doesnt matter how i rotate the graphics.. the forward direction is still the same direction..
the graphics can be upside down, right way up, or spinning in circles.. the navmesh will still walk towards the Z axis
Hey there guys, i just joined this discord and wanted to ask a question about adding a score to my game in C#
ya, u dont rotate the navmesh, u rotate the graphics..
- Navmesh
- Graphics
That's the code
yeah i tried both
for the sake of it
hey, so, how do I keep a button pressed even when the player changes screens?
I wanted to make it with a flag. When object collides with player it augments score by one
I just modified my script for an orthographic camera view and now it is as if I have a really far away near clipping plane
what would cause this?
ur near clipping plane..
sometimes its just a bug.. click an object and press F to focus on it.
but since thats in the gameview its probably just the clipping plane
public float score
void onCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
score += 1;
}
}
Good? just a shot in the dark here
nope
even if I set near clipping plane to 0 it still gets clipped
ofc, adapt score and player to how you want to call them
wont run.. ur function is wrong
;-;
I'll try
Score won't persist between different instances.
little lowercase mistake
what you mean? sorry i'm kinda new to c#
yeah screw this im a noob, ill let the pros help ya
Every object that has this script on it is a different instance of this script. Each one has their own score
If anything, you could update score in the Spawn function
ahah dw, i appriciated it anyway
and what gets clipped doesn't get affected by whether I zoom in or out
Oh right i see. Should i make a script "score" and attach it to every object? Or there's an easier way to do that
var next = Instantiate(...);
next.score = score;
next.collided = collided;```
That would still be each object with their own score variable
right x)
You should decide which one object should "own" the score, and have the other objects tell that script to update its score
Example: A metroidvania style screen transition, walking through the border of the room and going to the next scene. how do i make it still be walking when in the next scene?
ah negative clip planes
but id def try moving the camera arounda bit
didn't know that was possilbe but makes sense
lol ya, first time ive seen it too
If a negative clip plane fixes it then your camera is too close and you need to scooch it back
I wanted to make it much easier as of now. I just wanted to print the score over the console, so i do not need instantiate right?
negative clip plane was not the solution,,, I did the Ultimate Doom oob glitch
Hey everyone, I'm trying to do different states wether my player is walking when jumping or idle, but can't seem to find a way to calculate the x and y velocity at the same time using else if, does anyone have any way to enlighten me on this?
That was your Instantiate code from the Spawn function
well dang, u decided to use -5000?!
and camera is 150 units away from objects that are clipping... moving it back didn't help
and in fact the farther away I move it the more clipping there is
hello, how do I create a prefab asset with a script?
I was suggesting you update the next instances' values
Oh i see
ur camera is just wigging out.. ur values are probably really odd lol
if takes in a single boolean. If you want to check multiple things in one you'll need to use some logical operators
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators
just create a new camera and adjust it from a fresh start
thanks!!
There's the PrefabUtility class, but be warned that it only works in editor, and cannot be used in a build:
https://docs.unity3d.com/ScriptReference/PrefabUtility.html
its as if whenever I zoom out the screen doesn't grow
ah I probably asked the wrong question but i found the instantiate thingy
how are you zooming out
that would be creating an instance of the prefab, but yes you use instantiate
Okay yeah that's the way to do that
Just wanted to make sure you weren't trying to zoom a 2D camera by moving it in or out
🎉
what really gets me is that zooming in keeps the same area clipped
this is only really an issue when zoomed out
yeah I've googled a bunch but I'm pretty unknowledgable on cameras and my google searches haven't returned much
will keep trying though
give me ur ground size and ur camera transform and ill see if i get the same issue
is there an event function for when you save an SO? like OnValidate(), but for when you save it?
i have a ball that follows box and should be destroyed when it touches the square
- Use CompareTag
- https://unity.huh.how/physics-messages