#💻┃code-beginner
1 messages · Page 375 of 1
SoundPlayer.enabled = false(); isn't working, nor is SoundPlayer.SetActive.false();
well, that's not how false works
it's a literal, not a method
SetActive is also itself a method
So how would I do it?
SoundPlayer also doesn't seem like a component?
It's the name of the script
you can't disable a script
you disable a script component
you have to disable something that's actually on a gameobject
from there it'd be .enabled = false;, without the parens.
parens are for calling methods, which in c# will be in PascalCase (by convention)
here's my script, what am I doing wrong? the "nvm" was a false alarm
you shouldn't be using Component directly
oh
Component does not have a member called disabled. that property is implemented on the derived class Behaviour
you have a script that inherits from it, use that
but yes, use the actual type you care about
also you would have to set (missed that it's public, nvm), and probably name it more appropriate to what it isThisScript
oh and another thing, you do not want to use Thread.Sleep on the main thread 😉
also props/variables should be in camelCase to distinguish them from types and methods
also, Thread.Sleep would completely freeze the game if it worked
what's another option?
use a coroutine
Coroutines
just realised that i could use waitforseconds but C# doesnt like it :(
you can...in a coroutine
WaitForSeconds is a class. If you create a WaitForSeconds and yield it from an enumerator that's being run as a coroutine, Unity will wait for that long before resuming the coroutine
im super new to scripting so idk whats going on here
this is very wrong
even if WaitForSeconds was a coroutine (which is isn't), starting a coroutine does not delay the code after the StartCoroutine call in a normal method
and yes: you cannot make the OnTriggerEnter method "pause"
doing so means the game is frozen
ok this is really stupid, let me explain what i'm trying to do:
I'm trying to make it so that if a user presses a button, an animation plays that opens the gate. I have to wait a specific amount of time so the animation doesn't loop. Then I have to disable the script so the user can only open the gate once.
OnTriggerEnter will still run even if your behaviour is disabled, i'm pretty sure
just store a bool that tells you if you've already opened the door
and do nothing if it's true
what about the animation part? how will i make it wait
it will. physics calls keep running
ate up a good day or so for me to figure that out on my own
Oh crap thanks
@vocal fjord I skimmed so I might have missed what you wanted but if you want to wait for an animation, or to do something, can't you just disable or do whatever you want and then invoke a function with a delay to reactivate / do the thing?
For instance.. Disable the player controller so they can't move and then invoke a function to reenable it after 3 seconds?
Invoke is also an option, yes
it can be used to send a message to a MonoBehaviour after a delay
Probably an easy way to achieve it for someone new
Invoke is pretty simple to get working Elliot, just create a function with the stuff you want to wait for and then do
Invoke("<YourFunctionName>", 3.0f);
How do I poll the new Unity input system? I've read and re-read the documentation but I'm still lost on how to get the desired polling
private void Update()
{
var moveDirection = moveAction.ReadValue<Vector2>();
position += moveDirection * moveSpeed * Time.deltaTime;
Debug.Log("position " + position);
}
I never knew it would be this hard to make a door that can only open using a key 😭
this looks fine...assuming that moveAction has a meaningful value in it
show the entire script
It's really not that hard. Just a bool check, then the rotation or animation being played
Rotation is the hardest part for me, but even that has tons and tons of guides online
I followed a video and you need like 4 scripts for that or is that wrong?
I'm trying to receive and then set the animator to the appropriate float
I presume PlayerMovement is the name of the generated class
you should fetch the move action from that
the moveAction field has nothing to do with it -- it's a completely separate input action that only exists on this component
The number of scripts is incredibly irrelevant. You could do it as 4, or do it as one. You could break it up into 10 if you want
I would have a class for remembering what keys I have, one for interactions with objects in the world, and one for the door. Might abstract the communication between the interaction class and door with an interface or abstract class, but only if I'm going to be interacting with many different types of things
Okay noted, I'll get back to my code
like im watching these tutorials and they are awful like half of them don't speak/don't speak english I can't find a decent one lol
Did you go through learn.unity.com?
id rather watch an actual tutorial instead of reading on how to do it
you're going to have a miserable time if you refuse to read anything
Well, then you are in for an incredibly difficult journey if you want to do it the wrong way
But learn has videos. As I've told you mutliple times before
But once you complete learn, then you can just look at the docs for a raycast and... understand it.
Youtube is clearly holding you back a LOT
How do I fetch the move action from the script? It's a bit confusing to me, sorry
https://gdl.space/hayasesexi.bash
you're already doing it
controls.Main.Movement
this is getting an InputActionMap named "Main" and then an InputAction named "Movement"
Oh
You could assign that into moveAction if you want
In simplest terms, what is [SerializeField] doing here?
[SerializeField]
Transform hoursPivot, minutesPivot, secondsPivot;
hey, i usually work on windows but when i wanna test on iOS i pull the project on my mac and test
but for some reason the project on the mac have issues with the c#
can find some classes for some reason and act weird.
p.s i know there are different .net version on my windows(4.X) and mac(2.X) but cant find the same version for mac
do animator Controller Triggers stack?
like if i have
Controller1.SetTrigger("1");
Controller2.SetTrigger("2");
in the same method and i call them at the same time do they both activate or first trigger 1 then 1 frame after trigger 2
Both triggers will become set. At some point in update, it'll update the animator component which will check the current state's transitions, top to bottom, and execute whichever one it first finds true. At that point it will check the new state's transitions, top to bottom, and so on
So, they're both true, but it depends on the order you're checking them
oh ok
is this code AI generated?
"Don't work" is not really helpful. What do your logs say? What debugging steps have you taken? What is currently happening?
What isn't working about it
I'm cross posting here, I'd be eternally grateful if someone could help me with this (#archived-code-general message)
What do you have that moves the character
You haven't shown any movement code
Because you are changing it based on your rigidbody velocity. Where do you change that velocity?
What is the transition from walking back to idle
Show your logs
what do you mean where?
Where what?
in the console
I am trying to have the transform of RocketTurret1 be set to the exact same position as GameObject, however no matter what i try in the code it always sets to some random offset value. Ive tried setting it to Vector3.zero, Ive tried any combination of localPosition and Position, ive tried having the position it needs to be saved as a preset Vector3 and NOTHING has worked. Its the simplest problem ever but its just. not. working.
the localPosition is the position relative to the parent's origin point where as position is relative to the world's origin point
did you assign its local position to 0?
The code shown will put whatever object Child is at the same position as this object. The inspectors might not show the exact same value, since that shows the local position, but if you look at where the pivots are in scene view, Child's position will be at the same position as this object (unless other code moves them later)
that would only be true if this has no parent since then it's localPosition and position would be identical
The code example i showed was one of the many examples
no matter the combo of localPos and Pos it didnt work
both pos, both local, mix and match etc
if you assign one object's transform.position to another object's transform.position then they absolutely will be the same position
correct the code to do that, then show how you are verifying it isn't the same position
Did you try logging the worldspace positions of both after this operation?
thing is in the prefab the object is where its meant to be, and even if i dont change the values what so ever, it still gets offset
Oh, you're right, I read them both as position, since the thumbnail cut it off
also assigning the object's localPosition to Vector3.zero will make its position the same as its parent object
you still have yet to show how you are verifying the position is different
im getting SS now
These SS show the position of the parent and object after instantiating, as well as the code used in the example and the physical distance between them in the scene
Do you think it's worth it to use/learn the new input system? Or if I'm new I should stick with the old one
That depends on if you need to implement key rebinding or local multiplayer
I don't think I need it
and are you certain nothing else is affecting its position? such as a dynamic rigidbody with a positive gravity scale?
@wintry quarry do you recommend the old one for newbies?
wait a sec
also are you certain the Child variable is referencing to the correct object
bro... its 2am.....
your point being?
sorry for the time waste ig 😭 i forgot to remove the gravity scale from the rigid body
that was the longest hour of my life istg
How do I poll the new input system for ReadValue<Vector2> values in order to set my animator?
private void Start()
{
controls.Main.Movement.performed += ctx => Move(ctx.ReadValue<Vector2>());
}
// If we can move, then transform.position += Vector3direction
// We are adding in direction because the value is a 0 or 1 and with tilemaps each cell size is one unit size 1x1
// Same with the Y axis
private void Move(Vector2 direction)
{
if (CanMove(direction))
{
transform.position += (Vector3)direction;
animator.SetFloat("moveX", ctx.ReadValue<float>());
animator.SetFloat("moveY", ctx.ReadValue<float>());
}
}
ctx is local var "context" from another function, this would not work
As I said in the other channel, you do not poll with new input, unless you do it the completely different way I showed you
This is event driven
You could with .device ReadValue instead
but you should just use the events
From the documentation about Polling
You can poll the current value of an Action using InputAction.ReadValue<>():```
Yes, and that is different from what you have
That is pulling it from an InputAction
Which you can make a variable
You already have the callback set up though, so why not use that? It is way better
Oh I see your points
How do I utilize the call back in this context?
Nevermind don't answer that let me read the documentation and try to figure it out on my own
you're passing it in the "direction"
I have this attached to a gameobject meant to serve as a speed powerup that lasts 10 seconds, but after the player acquires the speed boost they never lose it. I was thinking it's because the object the script's attached to gets destroyed, yet the coroutine still runs after destruction so that can't be why. Do I have to pass anything to the player object to make it work?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class SpeedBoost : MonoBehaviour
{
public float SpeedBoostDuration = 10f;
PlayerController controller;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
controller = collision.gameObject.GetComponent<PlayerController>();
Destroy(this.gameObject);
StartCoroutine(SpeedBoostEffect());
}
}
private IEnumerator SpeedBoostEffect()
{
Debug.Log(controller.runSpeed);
controller.runSpeed *= 2;
Debug.Log(controller.runSpeed);
yield return new WaitForSeconds(SpeedBoostDuration);
controller.runSpeed /= 2;
Debug.Log(controller.runSpeed);
}
}
coroutine will not continue because you destroyed the object that started the coroutine
alright, so should I have the player call the coroutine using OnCollisionEnter instead?
I would make a script on player yes, call it SpeedBoostAbility or something, then call corutine there on pickup
so yeah basically run it on something you're not destroying
👌 thanks!
You could also start the coroutine on the player object like controller.StartCoroutine
Yeah that’s what I ended up doing
Got it. It might be better your way since the new toggle would be first then. Thanks!
Thanks. I'm not too familiar with naming conventions in Unity but after some reading, my aim was to add a non persistent event (added through code, right?) before persistent events (events added through the inspector?). In the end, I used methodinfo reflection to get the objects and method names for persistent events, created a new dropdown event, added my own non persistent event first, added the reflected persistent events then applied this new dropdown event to the actual dropdown. It seems to be working fine. Why am I doing this? Because I wanted to create a multi select dropdown feature for the base legacy dropdown and to do that, I needed to save the legacy dropdown changes in a list of int before any persistent events triggered, so I needed to add my own non persistent event to change the selected values first. I got it to work fine in the end. There are 2 quirks at the moment: the ability to reshow the dropdown values after you select an option and the ability to reclick on an currently selected item in the dropdown which does nothing by default. For the first quirk, using coroutine to wait for all toggles to get destroyed allow me to reuse the Dropdown.Show() method (which I extended to update the toggles and enabled all currently selected values) and for the second quirk, I detect which item was selected last and add a new click event on it to trigger the original click event. It works fine except a little delay to reshow the options after selection due to the fade in timer. It can be lowered to 0 but even then, you still get a really quick on/off effect on the options, plus a small problem of the scrollbar being reset if many options. But that's acceptable. With the new "isMulti" bool from the inspector, I can now change the dropdown behavior from single select to multi select and vice versa even at runtime.
Just above 🙂 I found a solution, thanks!
Can someone help me with something?
don't ask to ask, just ask . . .
Ok lol! How do i fix this?
anyone who has the time and know-how will help . . .
Don't ask if someone's available to help, just ask your question with the provided information and folks who are idle on the server-channel might be interested enough to provide some suggestions.
syntax error. you're either missing a semi-colon or misplaced one in your code . . .
is your IDE configured?
Ill show you the code can you tell me if there is a problem in the floats?
What does that mean lol.
your IDE should highlight the error in red . . .
!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
Your script editor should have highlighted the error
It will show you exactly where its messed up
How do i make it work with unity? I have visual studio
does EditorGUIUtility.systemCopyBuffer work in exported apps, or editor only
#💻┃code-beginner message click the visual studio one
Installed with unity hub one?
Make sure the work loads are installed
this is the incorrect script. read over this: https://unity.huh.how/compiler-errors/info
anything from Editor class is well editor only
How do i check
ops nvm
acshully i shall try
Execute the installer again and select modify. Ensure the work loads are installed and follow every step to make certain they're complete. There isn't too much. After that, you may be required to regenerate your project (also shown in the guide) and reboot the Unity Editor.
nvm I read it as UnityEngine instead of UnityEditor lol
Ok i will try!
Shown and explained in the guide, you want to make sure the Unity Gaming workload is installed - the other workloads are optional
(the others aren't necessary at all to do Unity game development)
if its windows only I bet you can just do Interop
whats interop?
Ya i clicked on that but just unchecked unity hub bc i have it already
basically you calling code into another library
the windows dlls
Is there more configuring to do while in unity?
thank, that sound complicated
Other than that, you'd setup your external editor if not correct and regenerate the project
apparently you can also copy the System.Windows.Forms.dll inside unity and use that built in paste system, idk how well it works
Clipboard.GetText();
Those would usually fix the problem
yeah should be easy apparently there is one specifically for unity already there
found this https://github.com/gkngkc/UnityStandaloneFileBrowser/blob/master/Assets/StandaloneFileBrowser/Plugins/System.Windows.Forms.dll
@ivory bobcat What should i check off here?
those two are fine
click Regen if you haven't already
Thanks!
@cobalt creek It works. Just gave it a quick test
awesom
I have it configured and working but i still dont know how to fix the script think u could help?
Anyone?
Can you show where the red squiggly lines are?
Im pretty sure unity is saying this ':' is not supposed to be at the end of this line but when i remove it it is saying that there should be ';' this at the end of the line
Ok, practice makes perfect. My solution was quite complicated and after checking more of the dropdown code, I found an even easier solution. No more listener changes, I simply changed the toggles method. Now they don't hide the options when click and it also calls my method to update multi values directly. So much simpler. The 2 quirks were eradicated this way too.
it would help to show us the error line of your !code, in question . . .
📃 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.
!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.
Oops
Ill show it
Its the character controller float
Here are the errors to
Their both on that line
you have float CharacterController characterController. you have two types for one variable . . .
Do i turn it into two floats?
[accessor] [type] [name] or
[accessor] [type] [name] = [value] . . .
Whats the accessor type and name?
[accessor] [type] [name]
You've got two types though
only you know what type of variable you want to create . . .
Why would your CharacterController be of type float at all?
do you know what a type is?
Tutorial idk
The tutorial did not suggest that
The tutorial guys worked with that float
go back and watch the tutorial. i doubt that is what they did . . .
Both float and CharacterController are types.
You'd only want one or three other as the type
then why didn't you just copy that?
you clearly know (and can see) that what you have is different . . .
Yup i very aware of what im looking at
Im very sorry 😭
WOW
would you look at that
I actually looked at my last error
and saw a capitalization error!
Now it works!
THANK YOU GUYS!
lol im very sorry abt that
Ok guys now i like actually have an issue
Im not clicking any keys and im just infinitly moving.
Show the code 🤷♂️
How do i send it here as a code?
you have to read the prompt (bot message) . . .
Message is to long
What?
The bot is too long to read? It is pretty short
!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.
Why did you do that?
Just use a paste site...
if you click the link we posted, it would've sent you to the same bot message . . .
bruh, it's too late for this . . .
A paste site
You read the section under "Large code blocks" and do that
Do not do the formatting
Read the section under "Large code blocks" and do that
I did
The codes here
I dont know what the problem is. My character just keeps moving in a certain direction and i cant stop it.
That's not a link to a paste site
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
That?
Try logging the value of moveDirection after you get it.
What do you mean?
Log the value of moveDirection after you get it
What do you mean by log
I mean log
Debug.Log
Debug.Log should literally have been the first line of code you ever wrote in Unity
Pretty much every tutorial would go over that before anything else
Im sorry im just new to coding and stuff so some things just kinda confuse me
What code would i use to log it?
that's how logging works
Do i need to log the value i want?
... _ _ _ _
What do i add after this?
No, you have to log a completely unrelated word like "Pumpernickel" and it'll just know what you wanted to log through sheer guesswork
Im sorry im new to coding 😭
hey I mean if you log a random value there's a small, but real chance it is the correct value on any given frame
Do i add moveDirection + 0f or something?
Why would you add 0 to it?
Just give it a bit of thought. What would adding 0 to it accomplish
gotta normalize it 🤪
Make it not move 👍
https://docs.unity3d.com/ScriptReference/Debug.Log.html
what does the first line of the description say?
Logs a message to the Unity Console
so what do you reckon debug.log does?
There are tutorials pinned in this channel. You should start there before putting random stuff in this channel.
Logs a message to the unity console
🤯
I just want help 😭 i dont know what to do
😭 then learn basic C#
you're clearly not ready to take on any projects
Like i know it logs message but i dont know what to put in the messgae
This channel is not for teaching you scripting basics from zero.
Again, Debug Log is the first line any competent tutorial would have had you write
We all start somewhere.
!learn might be a good idea
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Start here !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I don't know what you've done to start learning, but it's probably better to use this
would any tutorials possibly use print instead? it's equivalent in monobehavior anyways
Yeah, some of them might, but it's the same thing
print is a simplified wrap of Debug.Log in Monobehaviour
mhm I've heard that before
So it won't work in Scriptable Object for example.
better to learn Debug.Log since it works for non-Monobehaviour scripts . . .
fair point
I cant find out how to do it
Would the debug stop the player from moving continuously?
https://docs.unity3d.com/ScriptReference/Debug.Log.html
Read the page. This is what debug log does.
there are literal examples in the documentation
Should debugs be in void start()?
Are you trying to log a value in start
Im trying to make my character not move when keys arent being pressed so sure
how does this apply to start()?
@gloomy jacinth You still didn't even bother to look at the documentation page where the method is used inside another method.
You are asking questions that any introductory scripting tutorials covers. To spoonfeed you one here in chat would take hours.
While also showing no interest to actually try learning yourself.
@gloomy jacinth If you want to continue here, create a thread in case someone want to bother with personal tutorial for you. Otherwise stop with posts in the main channel.
Im really just trying to see how to do it. If someone could just give me an example that is used in my situation i will base it off that and learn on my own.
There's an example on the page
Three actually
three in one
I know but i dont know what objects its talking about in the line: Debug.Log("Hello: " + gameObject.name);
That would log "Hello: " + gameObject.name
I just dont know where and what other variables i would use to debug moveDirection
I told you what to log
How would you guys recommend finding the closest something is to something? Like the closest one object is out of an array to the current gameobject
Create variables for the current closest object and current closest distance set to the first thing in the list. Then loop through and check the distance. If it's lower than the current, they become the new current
place the objects to search in a collection: array, list, etc., then compare their distances to the target object . . .
When the loop ends, whatever's set to current is the closest object
consider just going through some c# basics first. you're trying to learn unity and c# at the same time
You need to log the direction to see if it's a value other than zero for x and y. If the values are zero for both and you're still moving, something else is occurring. If the values are not zero but you aren't pressing anything, perhaps you've got a drifting joystick connected to your system or something - relative to your input system.
The log will not fix your problem but it'll help you figure out what might be wrong.
So check the distance and see if its closer than the current gameobject?
Yes, keep track of the current "winning" object and distance. Loop through it and if it's closer, then it becomes the new closest
I think its script values because other games work just fine.
And quick question log messages show in the console right?
Did you log the values?
If you just need to compare closest one and don't need exact distance, you can use their sqrMagnitude of their vectors to compare.
Would this log work?
What would this accomplish
Literally what information does this give you
Im just testing how a log works 😭
Why do you want to see the words "This is a message" twice in the console
To LEARN how logs work.
Then test it, you don't have to ask us to run it for you
You can just run the code
Ya it doesnt work then
Need to install !ide properly as well
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I assure you that Debug Log indeed "works"
is this script attached to a GameObject in the scene?
The script needs to be attached to an object in the scene for it to fire it's callback methods: Start, Update etc
Oh there. Thank you!
I thought your IDE was properly configured?
It is
The image would suggest otherwise
#💻┃code-beginner message
Then why is this a screenshot of an unconfigured one
It would have proper syntax highlighting
It wasnt in a gameobject yet
It should be though relative to these images #💻┃code-beginner message
Hmm.
What if its just 1 winning object though and the others havent spawned in yet
seriously, at this point, you need to follow the basic tutorials from !learn. you're wasting everyone's free time with something you can understand in a few minutes by following along . . .
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Then you'll probably want to check it once all of the objects exist
I cant really find anything that shows how to get the value of an object with debug. Does anyone know?
What does [i] mean?
Do you plan to struggle the entire time in your game dev journey? Start learning properly by doing basics.
Just asking what [i] means.
@gloomy jacinth For the last time. Create a thread if you want to continue bumbling here.
You are wasting your and everyones time
Need help!
Is there anything I need to do to get the URP preset to work?
I removed the global light, and created an object with a sprite rendered with the lit material, and used a point light, but everything is still as if no URP is installed
EDIT: I wasn't using 2D lights (lol)
This is a code channel. #🔎┃find-a-channel
Thank you. I will look properly next time 🙏
Sorry for the mistake!
Whats the difference between string.Format("test") and $"test"?
i know both used to put variables in string, but idk which one should i use
$"{insertVariable}"; is called string interpolation. it's just a shorthand version . . .
so... there is no difference?
I don't think quotes should be around the variable itself
that's just a string
right?
that was just example
or is that not how string.Format works
ik that i need to put {variableName} in string
also probably look up tutorials for this stuff cause it's a pain in a butt if you havent
great idea
They both print test in your case.
In the following case, all 3 variants print "This is a test."
string value1 = "is", value2 = "test";
_ = "This " + value1 + " a " + value2 + ".";
_ = $"This {value1} a {value2}.";
_ = string.Format("This {0} a {1}.", value1, value2);
String interpolation is always better than the + operator
Welp, when i started learning C#/Unity i always used + operator for strings, i learned about $ thingy recently
If deciding whether to use string.Format or $, I, personally, use the 2nd one in most cases, and the 1st one when the parameters are too long
Use whatever is more convenient to you. The result stays the same.
Okay, thanks 🙏
if you need to actually concat strings, then use stringbuilder. But this would be when the input is unknown, like manually reading a text file for example.
as for string.format and string interpolation, you can get the same result from either. there may be small differences internally though. You probably wouldnt even run into this case but theres a difference here:
string _ = string.Format("Something {0} " +
"something {1}.", a, b);
// and
string _ = $"Something {a} " +
$"something {b}.";
The 2nd one uses string.concat even though both do the same thing and otherwise look the same
okay thanks
In a game jam atm and having an issue with Quaternions:
I want a quaternion facing in the opposite direction. It works in almost all cases i.e
Quaternion originalRotation = Quaternion.Euler(new Vector3(0, 90, 0));
Quaternion oppositeRotation = Quaternion.Euler(-originalRotation.rotation.eulerAngles);
oppositeRotation will be a quaternion with eulers (0, 270, 0) however, if the originalRotation has the euler angles (0, 0, 0) or (0, 180, 0) oppositeRotation will simply be that same exact quaternion as originalRotation
Quaternion oppositeRotation = Quaternion.Euler(new Vector3(0,180,0)) * originalRotation;
Accessing the Euler angle property will give you some angle that would represent your current rotation - it might be any coterminal angle.
You might be better off having a Vector3 field being your actual rotation at all times and simply assign to the rotation property (quaternion) - don't acquire the Euler angle from the rotation property.
How do oppositeRotation and originalRotation relate?
originalRotation : oppositeRotation :: transform.forward : transform.forward * -1
is what im looking to do
I'm simply asking because oppositeRotation is assigned the the euler angle of -existingConnector and not originalRotation
DIALOGUE SCRIPT: https://hatebin.com/ztscnoasdc
NPC SCRIPT: https://hatebin.com/ijqfactzph
my dialogue wont work, it keeps getting stuck at the first string of the array and it doesnt go to the next one
fixed in original message, was meant to say originalRotation there
This is what im doing but in 3d and everything is working except the opposite math when its those values
i was assuming it was a coterminal angle issue although i dont have a great grasp on quaternions
this is truly some code. im guessing chatgpt?
for your issue, add debugs. you could even just swap the inspector to debug mode and see is isNextClicked is true.
not chatgpt at all
ill try that
thanks
if(Input.GetMouseButtonDown(0) || i == 0) Guys this checks if i left clicked anywhere right?
Or if i is zero
yess ok ty
there is a lot you can simplify and improve on here.
Like cache that GetComponentInChildren, infact you dont even need get component. Just directly assign it in inspector.
That whole timer setup just looks so weird too, like adding and subtracting to it constantly.
and ill just suggest to use StringBuilder instead of concating strings like this, but that might be a bit above your understanding for now.
You really should have Debug.Logs around or use the debugger to solve issues like this though, theres gotta be one clear problem area. And that is likely the while (!isNextClicked) based on your description
Is there anything, which makes you think this code is written by ChatGPT, or are testing out your guessing skills?
whats stringbuilder?
A class to build strings
ill look it up cuz i never heard of it
just vaguely remember the person asking if chatgpt is good and from chat history seeing similar code before but also asking what it does.
Id be very surprised if this was from a tutorial, because of the whole timer stuff thats happening there. it feels very random
im not even sure of what it does myself, this must be the first time if (timer < Time.deltaTime) has been written 😅
tbh i got it from a website which explained the code thorougly
the math probably checks out but its definitely a unique way of writing a timer
Alright, you do indeed have a reason to assume it's written by ChatGPT
Then you should understand what this is supposed to do, right?
float timer = 0;
while (i < characters.Length)
if (timer < Time.deltaTime)
Because I don't
Oh, there is interval added in the condition
But, why..?
its more understandable if you just do something like this
timer += Time.deltaTime;
while (timer >= interval)
{
textBuffer += characters[i];
gameObject.GetComponentInChildren<TextMeshProUGUI>().text = textBuffer;
timer -= interval;
i++;
}
If deltaTime is somehow a lot larger than interval, itll also still instantly print out the characters it needs. The only thing is you'll want to rearrange this a bit, so its checking the value of "i" to make sure its not trying to access out of bounds elements.
But it's not going to run once if they have more frames per second than characters per second
E.g. for 20 & 10:
0 += 0.05;
while (0.05 >= 0.1) ...
well yea itll still need some check to yield. this part was just to simplify the timer so its not confusing
They should simply WaitForSeconds in a Coroutine, even if it's not going to be calculated too accurately depending on the frame rate
WaitForSeconds intervalWFS = new(1f / charactersPerSecond);
foreach (char c in line.ToCharArray())
{
// ...
yield return intervalWFS;
}
@frank zodiac
I need help, i have texture in this folder, but when i load it trough script as Sprite, it doesnt work...
Resources.Load<Sprite>("path/Shicka.png")
Is there any way to load it?
ah i see
look at what you have in the parameters. The path i can see in inspector and the string are completely different
https://docs.unity3d.com/ScriptReference/Resources.Load.html
yeah
i know, it was example path cuz...
And no im sure that this is right path i tested it
Have you looked at the Resources.Load documentation?
no..?
why not?
well you know it was an example path, how am i supposed to see that? when you show code, just paste what you have. its pointless to obfuscate it or hide details because you assume its correct
"var sprite = Resources.Load<Sprite>("Sprites/sprite01");"
Whats difference?
no file extension?
next time RTFM
okay
Hello everyone,
I currently have the following code to rotate my player around a pivot point. He does this for the whole game and it looks very smooth on the PC but as soon as I start the game on my mobile phone the rotation bends and doesn't look smooth at all.
transform.RotateAround(target.position, Vector3.forward, rotation_speed * Time.deltaTime);
i've already done a lot of research but i only started with unity and i'm not very familiar with vectors or quaterniums.
Does anyone have an idea?
its a 2d game by the way
Is this called in Update?
yes
Then there shouldn't be any issues
I thought the same
Are there any other factors affecting the rotation?
no not that I can tell it runs smooth as it should on my PC but not on my phone
What's the fps on your phone?
120
Could, you send a video of it?
This looks alright
If you're referring to the graphics, I think it's purposely worse in Unity Remote
it seems smoother on the record i dont know maybe beacause its not build jet ?
no I can see a diffrent in the smoothnes but its odd
I think it's smooth
The quality is just bad
And it's not your fault
Maybe with this as a comparison
Does anyone know how to fix this little thing ?
Looking fine too
What "little thing"?
I never went to any programmer school as its a hobby of mine (i study medicine), and i need help with this tiling problem
Maybe its an easy fix, but youtube was just not doing it for me
What fix? I see nothing apart from black walls and red arrows
Look at the tiles on the wall
You may need to explain the unwanted behavior
Basically on the biggest wall, we have like 10 of them, on the smaller one theres like 20 and on the smallest theres 50
Okay, I increased the lightling
(Heres one without the gradient for reference)
Looks like they're being horizontally stretched on the longer wall
Yep exactly whats happening but i have no idea how to fix it
Do you mean that the tiles should all have the same size?
Yep
preferably
There's probably some setting to have them not stretch (or squished) but rather tiled etc
Not really a coding issue though, maybe ask #💻┃unity-talk or some graphics channel
does anyone know why my character with Character Controller component doesn't collide with the floor?
not a code question
sorry 🙂
if you're sure it's something related to your code then you could post it here, but if you're just juggling components on the editor and having trouble with that alone then stick to #💻┃unity-talk
and provide more information on what you tried
ok ty
!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.
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
}
else if (Input.GetKeyDown(KeyCode.Mouse1))
{
spawnBullet();
}
}
how do i make it so spawnBullet() can only be called every 0.25s or something
A Coroutine has to be used
Or a timer
With its WaitForSeconds
You can also do it in Update with Time.deltaTime, as was mentioned by dlich
how to use that
Open your browser and search for "unity waitforseconds"
ok
If you search for "unity make a method be called every second", you'll even get a full tutorial
hi, im extreamly new to c# and unity and i was just wondering what void and public does?
voidis a method, which returns nothingpublicis an access modifier, which makes your variable accessible in every other script
void denotes lack of return type. public is an accessory modifier.
These things are covered in most places teaching you C# basics
In Unity public also exposes the variable to the inspector for serialization if it is serializable
is there no one function that removes all children from a gameobject?
Now there is
public static void RemoveChildren(this Transform value)
{
foreach (Transform child in value)
Destroy(child.gameObject);
}
According to this, DetachChildren unparents all children which is the opposite of what I want but good to know anyways
this does work tho thanks!
you said remove, thats what it does. what did you actually mean?
remove from the scene or from the parent?
"remove" is unclear here
hiya guys. we are having this error in our unity VR game and not sure how to fix it as its not letting us save latest changes in version control, how do we fix this error?
ah, no, no one method for destroying all children
does it allow you to view/resolve the conflict in any way?
no it does not
idk unity vcs specifically, but when there's conflicts you would have to resolve them somehow, by either accepting your changes, accepting the incoming changes, or merging them (which may be manual)
double clicking there doesn't work?
i was thinking if we remove pro builder from the project will that work?
conflicts aren't a one-off thing, they can happen whenever
let me try again
it..could fix it, but may as well use the opportunity to learn how to properly fix conflicts
found this from a quick google https://docs.unity.com/ugs/en-us/manual/devops/manual/resolve-merge-conflicts
My advice is to also get the proper plastic GUI, instead of using the unity package(or in addition).
processing merge its saying now taking quite a while
should get you there though
depends on the file size, i guess
is there a build in function that lets a navmesh only move with only 1 axis (Only X / Y)
do u mean a navmesh agent
Since it's a settings file, it shouldn't take more than a few seconds.
yea but, i'd thought to make the pathfinding a bit rigid by just forcing the agent to only move with 1 axis and not go diagonally
You can't change how the agent moves, but you can get the planned path and do whatever you want with it.
not that important but X,Y would be two axis
I think OP meant one axis on any one step of the path
That makes sense
current_heat is a float 100% same as effective_change so i have 0 clue what is a problem
syntax
you may be using a , instead of .

why this always has to be so simple
thanks anyway
shame the text editor gaslighted me for 15 minutes into thinking u cant multiply a float, instead of pointing the problem
Well, when you're a beginner you have simple issues. The more experienced you'll get, the more difficult problems you'll face
What did the editor suggest?
I'm sure your ide actually did give you a correct error. Did you try reading it?
I'm assuming semicolon to terminate/split the statements - it may think it's meant to be two statements.
something along the lines that this statement can only be read, added, substracted or changed type
How can I check if the navmeshagent stopped because of the stopping distance? (checking boolean isStopped doesnt work)
I think there's a currentpath you can check
yes thank you
good morning code crunchers 👋
hi right now they way this script works is by whenever the player clicks, they start a timer. when this timer is finished, a bool called "giveclicks" is set to true meaning that the game should add to the player's click count. however, right now whenever "giveclicks" is true, it adds to the clickcount every frame. i only want the game to add to the clickcount once then move on. how can i acheive this?
call OnClick when giveclicks is true
this makes the game add to the clickcount automatically though
no it doesnt, it sets time remaining to 0
yeah but wouldnt that just make the timer start by itself?
yes, but if you don't do that then the third if is always true, so givclicks keeps getting set to true
oh right
is there a way to not make it automatic but also not set the third if statement to true?
of course there is, just think about your logic
okay i will try
SteveSmith i fixed it!!! thank you for encouraging me to fix it myself
Isn't that so much better than me just giving you the answer?
Is it better to have Items as a class or as a scriptable object in a Crafting Game?????
Does anyone know how i can make this turn into a scope screen? Instead of having it look at the actual model.
Hi all, I really don't want to cross post, but I really need someone to take a look at this and see what's wrong, I can't get my Collision to trigger at all on the 'Tower' Object, but the exact same setup works perfectly fine on my smaller 'flying' enemies. I'm at a complete loss.
https://discordapp.com/channels/489222168727519232/497874196274348032/1248945834318495775
You could use a render texture I think (second camera at the 'front' of the scope and apply the render texture to the 'near' side of the scope?
why when i add custom get/set to variable it doesnt display in inspector
Some games also make the model invisible and overlay the screen with a scope image
Yes this is expected, Unity doesn't serialize properties, only fields.
You turned it into a property
Actually thinking about it, you'd want the second camera at the end of the barrel (not massive accurate in terms of realism, but would allow you to use a crosshair to accurately aim.)
i want run action whenever editing variable and onvalidate runs bit too much how can i do it property way
Would i put the camera at the barrel or other end of the scope?
Use NaughtyAttributes
Not with a property
At the barrel (where the bullet comes out)
scriptable object, so its easy to create new items
Okay, thanks!
But you would need to add any muzzle flash/bullets to a new layer and tell the second camera to ignore that layer so that it doesn't render them.
I dont think it works. I have the camera showing the end of the barrel on the scope. But my player randomly moves without key inputs and now my animation doesnt work and i fall through the floor.
I fixed the animation but i still just fall through the floor and move randomly.
Do you know how i could fix this problem now?
is there a way to tryparse a string to int which is bigger than int.maxValue and if it's biggger, clamp it to max value instead of returning false ?
Currently, it returns false if the string is bigger than int.maxValue but I can't figure out a way of knowing if it's false because it's too big or because the string is not an int format.
parse it to long
Umm......that's a new on on me I won't lie. I have no idea why that would happen.
Good idea. I went for double and simply clamp to int.maxValue in case it's also bigger than long. Thanks!
bit of overkill. you could also check the length of the string first to see the number of characters it contains. it should not be more than 10
Hello! I am a very beginner programer and I've been using many youtube tutorials and stack overflow posts to piece my game together. I recently ran into an issue when trying to add attack function(?) and animation.
this is the code I have so far for my player controls
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float movementSpeed = 22.5f;
private Rigidbody2D rb;
private Vector2 movementDirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movementDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
if (Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("isAttacking", true);
}
void FixedUpdate()
{
rb.velocity = movementDirection * movementSpeed;
}
}
the problem is when I added the
if (Input.GetKeyDown(KeyCode.Space)) { anim.SetBool("isAttacking", true); }
I got lots of errors(Ill send a photo) and I tried moving that section of code to the fixed update section but that also did not work.
In the animator I have set up my move/idle animation (which is the same in this case) and my attack animation with transitions between of "isAttacking" true/false. Thanks for all help in advance!
length can be 11
-2147483648, int min, though you can just check if the first char is '-'
!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.
you have not declared a variable called anim
@night owl is your IDE configured? you have a shite ton of syntax error
oh thank you! i did not realize I will try and add that
sorry but I dont konw what an IDE is ahaha
!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
Your code editor
assuming you're using one and not notepad
yes make sure to configure it so you can format your code properly
it will highlight errors for you
im so sorry to ask but is that what the lightbulb is?
Everytime I click it it just seems to undo my formatting
like visual formatting
which i had gotten from tutorials
screenshot what vsc looks like atm
yes i believe so?
why is not highlighting that huge error you got
You literally have an if statement outside a function
I think the problem is that I didnt declare the vari
nah man you got if statement outside a function
but it seems i have other issues as well
that was only a small part of the problem
your vscode is like partially working
make sure you updated all the extensions and try regen project files in unity external tools preferences
it should be lighting up like a xmas tree
the Unity one?
make sure you don't have the old Visual Studio Code package in Unity
!vscode
do a few checks here on this link ^^
many thanks i wilil try that
Always fun when you accidentally divide by 0 lol.
this is what it looks like now
oh and
its on 1.90.0 but 2.0.22 is the one under it and the one i have in unity
yes Visual Studio Editor is the package in package manager that is correct, make sure the Visual Studio Code Editor one in package manager is gone
Also Click Regen Project files too on that same page
this didnt seem to do anything? what should it have done
ideally refresh your csproj files
did you close vsc and open script from unity after you did it
no not at all
!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.
in vsc it does seem like it isnt connected to the unity project
you would think by now you have one of these memorized or bookmarked..
does the Output tab spit out any errors?
Copy/Pasting the ''' cause typing doesn't type the same characters
uh what kinda keyboard you have?
its above the tab and ~
as well as below escape
Well the 'open' quote mark yeah I have that, but I don't have the closing
oh sorry my bad
its literally the only slanted symbol
idk I typed in UK layout and that came out lol
I would think by now you should know what a backtick is
yeah wait look at this
u might have to use the code thing
like on the num pad?
or copy paste
or the links i guess which is what u were doing?
it says something abt pressing right alt key
oh oops i just followed the highlighted ones 😭
I've yet to see a keyboard without one, unless its some special 60 keyboard
im gonna stop trying to help
oh wait. lol. Sorry, I'm being a spanner. Yeah my bad, I thought they were two seperate symbols (open/close if that makes sense)
Long day and trying to do maths. lol.
did you try this
#💻┃code-beginner message
yes sorry i was waiting till this was resolved to continue
Anyway.........speaking of maths................Would anyone be able to check this please? It's breaking my brain at the moment.
So I'm getting the circumference of a circle, which works fine, then getting an angle increment based on the circumference and the size of the object(s) that I want to spawn in said circle at regular intervals (objects x/z size is 20 units/meters) so that the objects form a 'solid' circle at the outer edge of the play area.
Can't seem to get the numberOfPerimeterObjects to calculate correctly.
perimeterRadius = mapSize * tileSize / 2f;
perimeterCircumference = 2.0f * Mathf.PI * perimeterRadius;
Debug.Log(perimeterCircumference);
angleIncrement = perimeterCircumference / 20f;
Debug.Log(angleIncrement);
numberOfPerimeterObjects = perimeterCircumference / angleIncrement;
Debug.Log(numberOfPerimeterObjects);
perimeterCircumference / 20f is the number of objects, not the angle increment
Angle increment would be 360 / amount of objects
Ah yeah, that makes sense.
Yaaaay, Thank you. 🙂
how can i interpolate the markers above their heads properly? right now i just have it set as a world to screen point and have it follow that point exactly, which leads to some jitter
apparently using lerp is bad
like mathf.lerp
this might sound dumb but how much does it matter having visual studio code vs visual studio community?
as long as they are configured properly what you choose to write in makes no difference
oh ok interesting thank you
I still have not been able to configure mine properly
But instead I've tried to fix the code
Well you should fix your IDE first
if you are on windows then try using Visual Studio Community instead
its easier to get it working out the box
[SerializeField] private Image attackButton;
[SerializeField] private Image defendButton;
[SerializeField] private Image tradeButton;
[SerializeField] private Image exitButton;
[SerializeField] private Sprite attackButtonSelected;
[SerializeField] private Sprite defendButtonSelected;
[SerializeField] private Sprite tradeButtonSelected;
[SerializeField] private Sprite exitButtonSelected;
public void AttackButton()
{
attackButton.sprite = attackButtonSelected;
}
public void DefendButton()
{
defendButton.sprite = defendButtonSelected;
}
public void TradeButton()
{
tradeButton.sprite = tradeButtonSelected;
}
public void ExitButton()
{
exitButton.sprite = exitButtonSelected;
}
how can i make this more efficent
define "efficient"
less code same functionality
Hi! How can I determine if a point is located clockwise or counterclockwise of a ray?
what?
a ray is just a straight line
infinite
I mean like this
In semi-surface that is lefter or righter of a ray considering it's direction
green is the point and it is in clockwise part
Is there some built-in method for this, or should i just use math
why not just get angle between the two lines and see if its negative or postiive
I'll try, sounds good
Just trying to check if unity has something for it already
ops
you cant do findobjectoftype() for non monobehaviours can you
How can i manage this in a 2d game?
I want to make a classroom scene that plays a "cutscene" when the player first loads the scene, but then it turns into a normal explorable place.
Also do you guys suggest making a scene for every "room" or should every scene be a whole map?
Its an rpg game
I believe you want the cross product
trig still hurts my brain sometimes, gotta double check
looks like taking an angle with extra steps
The value will be discarded, only sign is needed, so i think checking angle as you said is fully ok
what makes it exactly special being a cutscene ?
all you're doing is manually moving the camera and disabling move controls
character not moveable / not present, secondary characters and camera moving in a scripted way
You probably want to play around with Cinemachine and Timeline
Timeline mostly for all the scripted animating
does invoke stop when timescale is 0?
are you talking about the MonoBehaviour invoke?
Yes
chinemachine is just camera programming right?
As for the timeline, idm scripting every scene
yea I mean, In scripting just like characters appearing / not appearing with animations n whatnot , you don't need it every scene ofc
Hey, how do I set a velocity on an instantiated clone?
the Instantiate() method actually returns a gameobject as well as instantiating it, so u can do
GameObject thing = Instantiate(params)
then u can reference the stuff on that object
like its playercontroller or whatnot
thing.GetComponent<Rigidbody>().velocity =
so, the prefab that is instantiated can be refered to that variable?
great, ty
You can Instantiate it as any type as long as it inherits from Object
o i didnt know that
ya skips the GetComponent call
ohhhh that is neat
as long as the rbPrefab is of Rigidbody type for example
yes ^ lol dont be assigning NavMeshAgents as rigidbodys
or anything silly like that
lol
this spline shall now be a navmesh agent!
identity crisis!
would be an epic cast
what should I put in "(params)"?
a bunch of meshes on a spline start chasing you nightmare fuel
prefab, transform, rotation
^ i think should be bare minimum
u can.. just (prefab)
but who the hell knows where that ends up
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html always check docs
awkay..
either check docs or if ur code editor tells u as ur writing
makes me think of that mimic asset for whatever reason
interesting, is it splines?
a good price 😆
heck ya, my favorite price
it has to be splines.
and a little bit of ik for good measure
wait.. ik-ish b.c i doubt its a rig
def some raycasting going on
the feet touching the walls and stuff maybe combine with ik or spline feet?
How do i fix this?
dont try to access/modify gameobjects that u've destroyed
But im make a weapon shoot and it destroys the game object what do i do instead
thats fine.. but once its destroyed what are u still trying to do to it?
should probably use a prefab gameobject.. and instantiate a new one
destroy the old one.. and let it be
u can share the script if u like..
!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.
wee need a slash command for codeblocks
I think 67 because it says im trying to reach a destroyed game object
The error says that. Then it says you should check your script if its null or should not destroy the object
btw you do know you can add a delay directly in Destroy method
its ur Explode() method
after that.. u shouldn't try to do anything else to that gameobejct
or do the delay Inside the destroy method
Destroy(gameobject, 1f);
^ destroy after 1 second
since it destroys on a delay, wouldnt it be colliding with more stuff before it destroys
and proccing explode again
private void Explode()
{
if (isDestroyed) return; // Exit if the object is being destroyed
isDestroyed = true; // Set the flag
ya
private void OnCollisionEnter(Collision collision)
{
if (isDestroyed) return; // Exit if the object is being destroyed```
yes thats probably whats happening
good that u caught it tbh
sometimes these errors can go hidden for a long long time
how can i interpolate the markers above their heads properly? right now i just have it set as a world to screen point and have it follow that point exactly, which leads to some jitter
the jitter might also be from ur camera not being in the same kind of update as them. ive had that problem before
well his whole scene would jitter if it was camera issue
yea unless just the markers are different
id use one of these.. w/ a modifier
then u can adjust that modifier however u want..
make it snappy.. make it lag behind a bit.. etc
should smooth it out abunch
What do i change about my code?
i showed..
create a boolean (a flag) to let it know its been destroyed (or that has happened)
when u do that set the bool to true;
and then on every function that manipulates the gameobject do an early returnif (isDestroyed) return; before any of ur other logic
when isDestroyed is true.. it'll just skip all the logic underneath it
Do i need to make a public bool or something for isDestroyed?
and that will let it eventually get destroyed w/o ur script still doign things to it
since only this script would be using it it could be private
Ok
ill try
It still gives me the same error
Heres the update code: https://hatebin.com/yggyfecyez
Hi, I tried to Build my project, but it gave me an error with a folder that is not existing...? Does someone know how to fix it?
Line 24 and 46
It still gave me there error
what are the previous errors
it needs to be done in all ur functions
https://hatebin.com/ivnonchplu i have this custom button script but its not working for some reason. i have 4 buttons; attack, defend, trade, exit. the functions are for when the mouse enters and exits each button
you need to check your scene list
It's right, that path does not exist. You need to assign another scene from the Build settings.
Update
Explode
OnCollisionEnter
anywhere the code is accesssing the gameobject needs an early return
you deleted a folder with a scene that would've been added to the build
so check your scene listi n the build settings to see what scenes you've included
either way the scene list will show any scenes that cant be found
What do you mean?
In my Actual gun script to?
Or in every void function?
why does ur gunscript modify teh bullet at all?
idk
it should only instantiate it.. and then the bullet script would be the one doing everything to itself
just asking
so no, the gun script wouldnt need to know if the bullet is getting destroyed
But do i add this: if (isDestroyed) return; // Exit if the object is being destroyed
isDestroyed = true; // Set the flag into every void function?
Good afyernoom clan
every function that the bullet is calling
the idea is to make the script not do anything to the bullet after u've said Destroy yourself
So then i can only shoot my gun once?.
the gun should be spawning prefabs.. (thats it)
the bullet should then take over and run its own code
the gun shouldnt care what happens to the bullet..
if thats the way u have ur stuff setup.. then thats the main issue
I come to give the best of my ability to contribute to the missions and whatever the clan wants to entrust to me. I am Latino I speak through a translator and I am also in Moomens and filth
No ya i meant bullet but will puting this code into the bullet script make it clone prefabs when i shoot or just only let me shoot once.
im confused.. u shouldnt need to add anything to the gun script..
mate. this is a unity coding channel. You're in the wrong server
no offtopic
Im talking about the bullet script
yea, if the error is being caused in the bullet script
So do i add that piece of code to ever void action in the bullet script?
when u destroy it.. (or try to) set isDestroyed = true;
and then any function inside that script.. needs the first line to be if(isDestroyed){return;}
that way if its been destroyed.. dont do anything to it.. dont make particles.. dont try to destroying it again. nothing
and then eventually it will get destroyed completely (along with its script) and then no more errors will happen
nice! 🙂
im pretty sure it was ur Knockback loop
since loops can take a min to finish.. it was erroring out.. b/c the gameobject would get destroyed b4 it finished or something..
idk.. just a guess
Where it said private void Delay() i added the code because there was only a destroy game object instance there and it worked
but the flag should help
coool.. good to hear 🍀
Do you know how i can make the gravity less easily?
Because i want bullet drop but its quite a lot right now
if u change gravity its going to affect everything in ur scene
common thing to do is apply a little force to the bullet..
(small upwards force)
check out this component
if u did +4.9 on the Y it'd make it fall 2ice as slow
since ur taking half of gravity and applying it upwards
Is anyone able to help me with this code?
It doesn't detect the fifth line in "frases" any idea why?
nothing wrong with the code. how do you know it's not detecting it?
It says it's out of bounds
Out of bounds of the array
show the full error