#💻┃code-beginner
1 messages · Page 74 of 1
thats what i am trying to do
how are you reading the rotation?
transform.eulerAngle.z
Debug.Log it, see if it matches wit the inspecotr value
if not, try localEulerAngle
or just use quaternions
void Update()
{
Rotation = Player.transform.rotation.z;
AssignAbilitys();
}
```where is the eularangle....https://gdl.space/iqaxulodax.cs
or the file is not updated?
its not completely up[ to date
localEulerAngels also breaks when going to 180 degrees
btw you dont need to check rotation in update, you check it only if you change the rotation and idk how you rotate player tf and the eulerangle.z may not be Exactly The Same as enum value, depends on how you rotate it
i locked rotation on the rigidbody so it won't rotate from terrain and changed the rotation with transform.Rotate(new Vector3(transform.rotation.x, transform.rotation.y, transform.rotation.z + 90));
i have also tried rotating with rB.rotation += 90
@tawdry nymph just use quaternions
i don't understand those
well, time to learn them then 🤷
we wont learn them for you 😄
Learn how to understand Rotation in Unity with this helpful video! Dive into the complexities of Quaternions and discover their functions, including Quaternion.LookRotation, Quaternion.Angle, Euler, Slerp, FromToRotation, and identity. Join Unity Forge in this informative video and unlock the secrets of Rotation/Quaternions!
Chapters:
0:00 Stor...
how can i set up chunks and make them load in and out near the player
You don't exactly need to "understand" them. They're extremely advanced math that honestly I think almost nobody here understands.
whats that thing in C# called with the : that replaces if statements?
its not a switch is it?
ternary operator?
it's just cleaner
like maybe better performance or something
but if its code that im working on myself and i find if statements easier, its prob better to stick to that right?
if it's easier for you then yes
i guess what im asking is, its the same thing as if statements and just down to preference ultimately?
Just that Euler angles break sometimes and do very weird stuff, particulary when doing any logic on x/y/z and we need to use quaternions instead. But Unity handles the complicated part under the hood.
yes
that works?
why not
yeah i think i understand how that works
adult = age > 18;
just so weird i never thought of it before
we learn something everyday ;p
for real
how can i set up chunks and make them load in and out near the player
that's such a generic questions without any context
with several valid approaches
make a chunk class with list of objects in it, enable/disable it based on colliders, distance to player etc
basically just load/unloads objects based on certain conditions you want
Shouldn't this work by destroy any object that touches the collider?
Basically I have set up a box collider around my playing area to destroy any stray projecticles
yes, as long as the conditons to trigger OnTriggerEnter2D are met
trigger events are only sent if one of the Colliders also has a Rigidbody2D attached
well if it is disabled then nothing will collide with it
then make a ChunkManager
and store all chunks in that
So it doesn't matter if this "death zone" collider doesn't have rigidbody2d?
atlesat one of the colliders has to have rb2d
and the one with OnTriggerEnter2D function muse be set to isTrigger obviously
Can anyone help with why my On Click() Event is not working for a button? https://gdl.space/huceyugimo.cs really only care about the first line of code under Input1(). Its not even executing that. not sure what is going on
do you have EventSystem in the scene?
i dont think so
then it won't work
the guide im following is pretty old (8 years), is that something newer required in unity?
with an event system in the scene buttons wont work
are you using the brackeys tutorial?
without it*
Nah, its a guy doing a turn based battle system tutorial
my bad lol
yeah just add an event system and it should work
type this in the hierarchy
t: EventSystem
sorry if i broke up aquestion but i just need a quick help in this,
so i have a string based of :
"blabla 0lasdldfsjndfsjd9
blaablaa 0jdnljjanfdnsdlfsfs9"
and i wanna replace the parts between 0 and 9 (including 0 and 9) using regex but i cant figure out the pattern... any help ?
0*9, should be some pattern like this
btw a simple two pointers algorithm can solve it
string pattern = @"0.*?9";
i guess?
then just Regex.Replace(yourString, pattern, replacement)
but why not just use variable in this matter?
string someString = $"blabla0{variable}0faf";
then you can just put any string variable you want
or ints, floats
oh .* i mess up with wildcard, is "?" necessary? since * is zero or more previous char
alright! this works just perfectly
im just curious how
Thanks! that definitely fixed it, I guess this EventSystem wasn't required when this video series was published, he didn't have one in his
nah its not neccesary
? is just non-greedy
this only replaced the 9..
without ? it onl replaces the first substring
"blabla 0lasdldfsjndfsjd9 blaablaa 0jdnljjanfdnsdlfsfs9"
it will only replace the first part
with ? it will replace both
yes my pattern is searching for (zero or more of) "0" and following by "9" eg 9, 09,009
So for some reason I cannot drag my audio into my audio source into the inspector... any idea what's happening?
It's the right format (.wav)
your wav file is an AudioClip, not an AudioSource. AudioSource is the component that plays an AudioClip
How would I use coroutines for cooldowns etc. when I want to pause them as soon as I open the paus menu? I feel like there is a better way than yielding wait for seconds and then checking if the game is paused or not
if you're setting timeScale to 0 when you pause the game then you don't really need to change anything since WaitForSeconds will be scaled by the timeScale. If you aren't though you can instead put a timer loop in there that just increases a float by deltaTime on frames the game is not paused. you will need to check whether it is paused doing that but it will at least be accurate as opposed to using WaitForSeconds and just checking if the game is paused after the WaitForSeconds is complete
Ohh that's practical. So I will make use of timescale
Or multiply that Time.deltaTime by your own cooldown time scale which you set to 0 on pause, since using Time.timeScale is "global", so all other code using Time will "freeze"
Because I don't want to freeze animations in the pause menu and such right?
Right
Sounds good! Maybe I will try to create an interface or something for pretty much anything that is affected by pause
this is effectively the same as my second suggestion of a timer loop
True
But shorter
no need to check anything
just multiply by timeScale
it will either add 0 or deltaTime
For some reason my audio is playing at the beginning and end of the word sequence not the end, any thoughts?
please share your !code correctly. nobody wants to scrub through a video to try and read it
📃 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.
the beginning probably because the audioSource is set to play on awake
There's an if statement preventing that
Play On Awake is a property on the AudioSource
for what purpose? but also you can just drag it directly into a serialized field
beginner at prefabs but ty
although typically you'd want to separate your colliders onto different child objects
if you have two on the same GameObject you need to drag the one you want into a variable field manually. also, don't put more than one collider on a GameObject . . .
ones a trigger ones not idk how else to do this ;s
audio source component has Play On Awake selected by default. you probably need to uncheck it . . .
you haven't even bothered answering the first question i asked. there's probably a better way to do whatever it is you are trying to do
Yeah that's what it was @cosmic dagger
But I'm wondering why it plays after the user hits enter, not before as intended
if (readInput.currentWord == "りんご")
{
audioSource.Play();
oldImage.sprite = apple;
}
You'd think it would play before the image is shown
it will start playing the same exact frame that the sprite is assigned
But the game is showing the sprite but not playing the audio
Not until after I click enter
you're probably just repeatedly calling that method which is restarting the audio clip over and over until you stop editing the input field
and by probably, i mean that is exactly what is happening since you call it in Update 😉
only call it when the currentWord variable on your ReadInput class changes. i assume that is what your currentWordChanged event is supposed to be used for despite it not being used at all
Yeah I didn't understand how that works
Is there a way to get the remaining amount of seconds when using WaitForSeconds or would I have to store it as a variable in seconds and only use WaitForSeconds each second? I'm asking because when I exit the game I would like to store the remaining cooldown
no, use a timer loop instead
don't use WFS at all, store the time in a variable and yield every frame . . .
Why is it bad practise?
why not
nothing bad in both approaches
because they can't do the thing they want when using WaitForSeconds
yes in this case
but he said dont use WFS at all ;p
clearly referring to their issue and not every single instance of anyone wanting to use WFS
because they need to insert a specific time when using WFS and that won't allow them to get the time reamining . . .
a loop that adds or subtracts deltaTime from a variable
srry if im breaking a question...(again) but- what could be the regex pattern to detect whether the line of a text file doesn't start with an "A" (capital AND lower case) ?
^(?![Aa])
^ - start of the line
?! - negavite assertion
no actually it checks capital or lower case
no nvm
its good
then you can do like Regex.IsMatch(string, pattern) store it in a bool
and do whatever you want
gotcha! ill test stuff and brb
public class Timer
{
private int baseTime, currentCooldownTime;
public void StartTimer() => StartCoroutine(Timer);
private IEnumerator Timer()
{
currentCooldownTime -= Time.deltaTime;
if (currentCooldownTime <= 0) DoSomething();
}
}
Do you mean something like this?
Ohh so in update and then with a while loop?
Update() is not necessary
yes, but without the loop ;p
public float timeRemaining = 10;
void Update()
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
}
}
pick one or the other. Update without a loop or coroutine with a loop
float cooldown = 3f;
private IEnumerator Timer()
{
while (cooldown > 0)
{
yield return null;
cooldown -= Time.deltaTime;
}
}
```
that wont work
in his case
ok nvm it will
why not, cooldown is a field so they can access it when the coroutine ends or is canceled
well it depends what does he mean by "exiting the game"
Ok thanks everyone :) If both ways are viable I think I will use the update one because I don't like having to yield null for "no reason"
Both work, but keep in mind that Update() runs all the time, even if you don't need it
Coroutine only runs when you need it
It's basically an Update() but for temporary tasks
so basically the File is a lot of lines.. so im splitting the file by lines and checking them one by one but for somereason it seems to match up with other words that start with a ? or perhaps not even check them ??
private string Pattern = "^(?![Aa])";
private string[] STR;
private string FinalSTR;
void Start()
{
STR = OriginalFile.text.Split("\r\n");
}
void Update()
{
for (int i = 0; i < STR.Length; i++)
{
FinalSTR = Regex.Replace(STR[i], Pattern, "");
}
}
void LateUpdate()
{
System.IO.File.WriteAllText("Assets/Main Assets/Turkish/AlphaSorted/" + "A.txt", FinalSTR);
}```
three backticks to format code
i dont understand
and why are you doing this in Update and LateUpdate?
im not exactly sure if it matters im just tryna sort a word bank into different files...
but do you need to do it every frame?
you replace the final string every frame with regex patterns
and every frame you write the same final string to the A.txt file
also afaik regex is not really optimal to use especially every frame with a loop additionaly
uhh- how could i approach this then ?
Just split it and write once
or whenever you need
there is no need to change it and write every frame if it's the same
same with for example healthbars for your game, you don't need to set the fillImage every frame to match the current hp, just do it when player takes damage or heals
does anyone know why this object is spamming the very start of its sound effect while its loaded? I don't see anything here in the script that would cause it...
Can confirm the sound file works fine when played standalone
we can't hear any sound
unmute the video and watch 4 seconds of it
public void OnPointerEnter(PointerEventData eventData)
{
audioSource.Play();
imageComponent.sprite = image2;
}
comment this Play()
and turn off playOnAwake by default
you are constantly playing the clip
that's why it's looped in the beggining, cuz its starting again and again
put a debug.log in OnPointerEnter
i need it to check every line of the textasset tho it only checks the last one, why is that?
moved it to start like this :
public TextAsset OriginalFile;
private string Pattern = "^(?![Aa])";
private string[] STR;
private string FinalSTR;
void Start()
{
for (int i = 0; i < OriginalFile.text.Split("\r\n").Length; i++)
{
FinalSTR = Regex.Replace(OriginalFile.text.Split("\r\n")[i], Pattern, "");
}
System.IO.File.WriteAllText("Assets/Main Assets/Turkish/AlphaSorted/" + "A.txt", FinalSTR);
}```
I added audioSource.playOnAwake = false; to start
and the onpointerenter is now
```public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("Test");
audioSource.Play();
imageComponent.sprite = image2;
}```
The debug runs fine and the sprite from the mouseover is fine, but the audio never plays
and if i check play on awake it goes back to playing the sound on repeat super fast
because you are overwriting finalSTR
at each iteration you are replacing finalSTR with the result of the regex for current line
meaning finalSTR has the last line stored after the loop completes
you understand? 😄
FinalSTR += Regex.Replace(lines[i], Pattern, "") + "\r\n";
try sth like that
you should use stringbuilder this case...
So I'm trying to call my ChangeImage method without using Start or Awake how do I go about doing that?
https://gdl.space/vicihajuqe.cs
suppose you have 1MB file and 1K line (1KB pre line), you generated 1K,2K+3K+...+999K bytes garbage in total... (1K=1000 and 1M =1000K by disk manufacturers)
bro fr learn some basics
we spent long time on this lol
I'd go through C# tutorials first (checking pins here)
for example
https://learn.unity.com/project/beginner-gameplay-scripting
how can i set up chunks and make them load in and out near the player
references is how you can call methods in other objects. What we did last time is does it with an event
why are you asking this again
then just write what are you confused about
and what have you done so far
and what are you struggling with
instead of such general question
so I thought of making a list for all of the chunks and when the player get close euogh to one it loads in but I dont know how to reference transforms to a list or array
public TextAsset OriginalFile;
private string Pattern = "^(?![Aa])";
private string FinalSTR;
void Start()
{
for (int i = 0; i < OriginalFile.text.Split("\r\n").Length; i++)
{
FinalSTR += Regex.Replace(OriginalFile.text.Split("\r\n")[i], Pattern, "") + "\r\n";
}
System.IO.File.WriteAllText("Assets/Main Assets/Turkish/AlphaSorted/" + "A.txt", FinalSTR);
}```
this literally does nothing- whatt-?!
so many arrays being allocated 😬
and string
uhhhhh-
every time you do OriginalFile.text.Split("\r\n") it allocates a new array. and you do that each iteration of the loop
much like how it was pointed out that you are allocating strings each iteration. but this is even worse tbh

private string Pattern = "^(?![Aa])";
private string[] STR;
private string FinalSTR;
void Awake()
{
STR = OriginalFile.text.Split("\r\n");
}
void Start()
{
for (int i = 0; i < STR.Length; i++)
{
FinalSTR += Regex.Replace(STR[i], Pattern, "") + "\r\n";
}
Debug.Log(FinalSTR);
System.IO.File.WriteAllText("Assets/Main Assets/Turkish/AlphaSorted/" + "A.txt", FinalSTR);
}```
does this do ?
(prbbly not)
that's better. though you can split the string inside the same method you are operating on it.
you're still allocating a new string for each iteration of the loop though
i have said that you should use stringbuilder if you want to append string continuously
idk what a stringbuilder is-
how to not allocate a new string for each iteration again ?
google
though i will just write a simple two pointer to split the string by "\r\n"
use stringbuilder as was already suggested
Does anyone know good tutorial for like, a classic RPG set up? Like top down, camera moving with the character, that type of thing
I really hate programming👍
well don't do it then, no one is forcing you to
my friends
get better friends
anyways is there a feature to use strings to call specific function
why would you want to do that
"Good" can be subjective, there's like 100 clones of these tutorials , what exactly are you looking for that they don't provide?
so i can have a function where i change the string with inputs and don´t instantly call the function the string stands for
Asking about your attempted solution rather than your actual problem
manipulate your own vertices
How?
Do you have links?
i wanna make a top down shooter and wanna change my weapons
and how is a string relevant to that?
so i don´t instantly call the specific shoot function for the weapon when changing the weapon and when pressing the shoot button it redirects me to the specific function
i think my brain just suffered a malfunction reading that
i feel like you barely grasp how code works if you think using strings is somehow going to prevent you from calling a method
https://learn.unity.com/project/beginner-gameplay-scripting
@fierce mortar
quick question. is there a way I could trigger a button OnClick() through event triggers?
you mean IpointerClickHandler?
just call the function the button calls 🤔
button.onClick?.Invoke();
events can only be invoked by the object that owns them
well it's a unity event, not a system one
im using the new input system
ah well he said through event triggers, not code, mb
I don´t know how I can change my weapon without directly calling the specific shoot function for the weapon, and because of that I thought there is any way that when changing my weapon i could attach the name of the weapon shoot function to a string. And then I thought, with my stupid coding beginner brain, i could maaaaaybe convert this string to a function name to call the weapon specific function, when i pressed the Shoot Button. I know what a string is I´m just not experienced enough to know if you can change a string to a function name. Hope this was finally understandable enough.
what do you mean by "the specific shoot function for the weapon"? have you gone and made completely unrelated classes for each of your weapons instead of using a common base class that declares the Shoot method that each of the derived classes overrides?
polymorphism C# is what you should take a look at.
You basically need a base class or interface that has a method called Shoot(), then you create classes that derive from that for all the different weapons. Your player then has a field for the base class to which you can assign one of the guns to.
Then you call Shoot() on that variable and it will call the correct Shoot() function
how can i assign classes to a specific field
enter interfaces . . .
or you can use a base class that contains a Shoot method . . .
there are beginner c# courses pinned in this channel if you do not know how to assign something to a variable
inheritance vs composition 🥵
composition FTW, but inheritance is still existent . . .
haha yeah interfaces are awesome!
thank you guys that really helped, gonna try that tomorrow (gonna try everything without doing beginner courses )
gonna try everything without doing beginner courses
that's a good way to guarantee you are going to struggle
and now this makes more sense
i don't know anout that last part. at least learn and understand what the terms/concepts are . . .
It doesnt work but I dont know why
using UnityEngine.SceneManagement;
public class SceneTransition : MonoBehaviour
{
// Name of the scene to transition to
public string nextSceneName = "Scene2";
private void OnCollisionEnter(Collision collision)
{
// Check if the player (or any other object with a collider) has collided with the trigger
if (collision.collider.CompareTag("Player"))
{
// Load the next scene
SceneManager.LoadScene(nextSceneName);
}
}
}
which part doesn't work? some of it, all of it? details about your question help give better results . . .
The player dosnt teleport too scene2
reference things to a list? do you mean how to access an element from the collection: list, array . . .
im gonna look into tutorials about classes, but the thing is that i already watched a lot of beginner courses and know the super basic stuff like variables
like wehn you make a list you put objects into the list in the code
you can follow the link boxfriend suggested from their response . . .
oke dokee thx
thx
i know why now i forgot the 2D......
variables are only one concept. it's totally different from reference type, value type, classes, methods, properties, interfaces . . .
so i have chunks that i want to render in and out and I make the chunks in another script so they are not in the scene view
okay, so you want to add object to a list?
in code
thats why i said “like” variables
sure, what have you tried or google? just asking cuz if you search "how to add to a list c#," you'll get tons of answers . . .
you can swap list with array if you have that. make sure you know the difference between an array and a list cuz those collections are used differently . . .
ok so that sadly didnt work because i got mixed up a couple of things. is there another way to trigger a buttons OnClick() with the new input system?
to trigger a button's OnClick event, you manually call it. you can do that from anywhere as long as you have a reference to the button . . .
why did the event on the EventTrigger you were using not work? that would have worked just fine if you connected the same method to it that you connected to the onClick event
ok so
what i wanted to do
was use these
for the event trigger
EventTrigger is entirely unrelated to your input actions
and those are separete from the triggers
yeah i only realized that after
you can use a PlayerInput component or your own component to do that
i recommend looking at the documentation pinned in #🖱️┃input-system to learn how to use the input system
your PlayerInput component will have events for each of your actions. you can link the method you want to call from there . . .
Can I add this script to the floating joystick to stop it from spinning in circles over and over when I look left and right and hold it with my finger?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class FloatingJoystick : Joystick
{
[SerializeField] private float rotationSpeed = 5f;
[SerializeField] private float rotationLimit = 80f; // Adjust as needed
protected override void Update()
{
base.Update();
// Limit camera rotation based on joystick input
float horizontalRotation = inputVector.x * rotationSpeed * Time.deltaTime;
float clampedRotation = Mathf.Clamp(transform.eulerAngles.y + horizontalRotation, -rotationLimit, rotationLimit);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, clampedRotation, transform.eulerAngles.z);
}
protected override void Start()
{
base.Start();
background.gameObject.SetActive(false);
}
public override void OnPointerDown(PointerEventData eventData)
{
background.anchoredPosition = ScreenPointToAnchoredPosition(eventData.position);
background.gameObject.SetActive(true);
base.OnPointerDown(eventData);
}
public override void OnPointerUp(PointerEventData eventData)
{
background.gameObject.SetActive(false);
base.OnPointerUp(eventData);
}
}
hey guys, I have this if: cs if (_uiManager.currentTime > 60 && _uiManager.currentTime < 70 && _canSpawnSkel){ _coroutineSkel = StartCoroutine(SpawnSkeletons(12)); _canSpawnSkel = false; } but even if the currentTime is like above 80 it enter this if.. what am I missing here?
log the current time inside of the if statement to check its value . . .
Why not just try it and see? You coded it 
no way for us to tell if that will happen since we don't have the project or any of the materials . . .
you have to test it and see what happens. based on those results, you can see or tell us what occurred instead. then we can probably help with fixing the code since we have a result from the test . . .
I am trying to get the unity starter assets fps controller to stop spinning in circles with the lookpad joystick
floating joystick
use links to paste your !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.
for some reason a lot of times my programming app likes to suddenly be weird and when i wanna type something after something else, it instead replaces that something with something else. like if i wanna type space after print it replaces the t with space how do i fix this?
Hit Insert on your keyboard. You accidentally switched to character replace mode
oh thanks
skipped right over the part where you were suggested to use a link and where the bot says how to post large blocks of code
aaa
Beginner
Uses interface explicit implementations, lambdas, and dependency injection
Something doesn't add up
brah, you need to be more specific. What is not working? What is happening, what do you want to happen?
what is not right about it? does smth not work? also, this isn't a link but a wall of text (large code block) . . .
do you just mean code formatting or naming convention/guidelines?
again, https://gdl.space/adokecaxew.cpp, I am a beginner and I would like to know what is not right in my code. In short, I want to mention that there will be different types of ratings in my game. I would like you to tell me what you see wrong here and what you can recommend?
work,link?
(remove the "Hello" at the end of the link)
Now onto being more explicit, you need to say if you're having errors or whatever
what you can recommend, for performance?
are you actually experiencing a performance issue?
we can't determine if anything will work based off the code because i don't see any Unity methods. are you looking for smth specific?
I would like to know if I have structured this code correctly from a technical perspective, I mean in terms of code professionalism
i can say that you use don't unsub from the events that are subscribed in IStartable.Start() . . .
and they are lambdas, so you don't have a reference to the method/delegate to unsub . . .
if they remain until the application closes then it won't be a problem . . .
like that?:
No the events you subscribe to in IStartable.Start(), you need to unsubscribe from them when this instance is not needed anymore
okk thx for comment
does the method UnsubscribeFromEvents actually unsub the methods (lambdas) from the events?
lol, I basically just copy-pasted Random's comment
You can't unsubscribe from a lambda (unless you keep a reference to it somewhere), so I assume that's not the case
yep, they need to store them as methods . . .
if you want to be picky, const variables are PascalCase and private variables prefixed with an "_" — if following the Microsoft coding guidelines . . .
i have other rights ;))) but ok thx
Wait hold on there's something weird in this code
The rating loading on line 65 will overwrite the loading made on 64, they target the same variable
Same for saving
yeah, it's not a big deal at all, haha . . .
hmm ok
also, why do you call UpdateAndSaveRating twice in a row?
ahhh, SPR2 just mentioned that . . .
For "good" and "bad" ratings, but they need two properties because they're stepping on each other right now
oh, then that's fine. they use different keys as arguments . . .
You're always saving/loading the bad rating metric, because it's the last one in the subscription list
"I want to use a single variable for the rating system, where at the beginning of the game, you choose to play for a 'badrating' or 'goodrating,' meaning you can be a good pharmacist or a bad pharmacist, and 'currentRating' is shared, as ideally they should not intersect.
Well you need three properties then. One for the good rating, one for the bad rating, and one for the one you'll be choosing when the game starts
void UseRating(Rating r) => CurrentRating = ...
For a death screen, should the preferred approach be to make it its own scene and load that asynchronously on death, or make it an overlay and set the delta time to zero?
So I'm making a 3D top-down view RTS game. I've watched a tutorials on how to do a selection box to select my units, but all of them are in 3d using Physics2D.OverlapAreaAll(), is there any replacement for that in 3d?
yes that takes the Center
i need 2 points (startPos and endPos)
and make rectangle based on these points
You can calculate the points and get a center
yup, get that center . . .
Does anyone knows how could i transpose textures from a terrain to a plane?
Cause i can't use the shader on a terrain due to it has no materials...
how would I stop this during the 5 seconds to not disable the game object?
StopCoroutine
still sets it to not active
Show code then
the stopcoroutine is functioning it still runs the next line not sure how to get between it
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
As you can see in the docs, you need to cache the coroutine to actually stop it.
are you sure StopCoroutine runs? try caching the coroutine in a variable . . .
You can still use a material with the mesh data texturing, but not sure about the question.
how?
make one
Oh, then you do have a material
but thats the building... not the terrain
i don't know how to apply it to the terrain too
oh, you're using actual terrain tool ah
i don't know how... but i need to apply the shader to the terrain... any ideas for that?
or just convert the terrain into a plane or something like that
if it's posible hehe
real quick, i have a line of code that says "cam.GetComponent<Animator>().Play("introRunCam");"
im trying to replay the animation when i press a button ( i already have a function and stuff ), how would i achieve this?
Doubtful, as for the shader question it's probably better to ask in #⛰️┃terrain-3d. May need to google around a bit
thankss
link this function to the button's on click event?
whenever i replay this code the animation doesnt restart
🤷
Whenever I have one item equipped (eg. axe) and then i try to switch to a different item (in this case it's a wood log) it wouldnt switch until i free up selected slot
Sorry I absolutely suck at math, what is the best approach for this kind of motion?
Non-physics I mean
quick question, which is better for unity, javascript or python
I mean unity is in C# but just learn whatever programming language you want
can you use python or java?
Not really
alright, thanks!
I started out in Python as well but switching to C# wasnt too difficult
are they like the same?
Once you'll learn the basic concepts, the differences in syntax aren't really a big deal
so if I am to learn python, I basically learn C#
If your goal is to use Unity, then learn C#.
alrighty, thanks!
So like just learn the base concepts like variables, methods, classes, etc. and you're good to go for Unity
Saying it because couple of years ago when I first started learning Unity, I had no clue about programming and I just copied code
learned absolutely nothing
ok ! so i want to create actions for my player movement
but i cannot select the bind "right stick [gamepad]" for no reason
and "Delta [Mouse]" to
Ask in #🖱️┃input-system and provide a screenshot of the Input Actions Asset editor with the action you're trying to bind visible
ok !
hello, im trying to implement a simple fps camera into my scene so im watching this video. it kind of works as intended but for some reason, when i start the game, the camera starts by always pointing down. idk if this is a silly question but i cant find the reason it's happening. https://youtu.be/f473C43s8nE?si=jkmRJOJOAOmgk22g
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
two things: first, the reason the camera starts by pointing down is because when you press the play button then move your mouse down to the game view, that is happening within the first frame so immediately the camera is rotated downward because of your mouse movement.
second, don't multiply mouse input by deltaTime. mouse input is already framerate independent and multiplying by deltaTime is to make something framerate independent. by doing that multiplication you are requiring your sensitivity to be about 100 times higher than it really needs to be and you end up with stuttery camera controls
oh and obligatory "use cinemachine"
i knew it was something silly like that. Thanks for that and you are right on that second part. had to change the sens to 1000 for x and y to get a decent camera speed
Hey guys, when I use this snippet code cs private void Update() { if (_player.playerCurrentHeath <= 0) { Scene currentScene = SceneManager.GetActiveScene(); SceneManager.LoadScene(currentScene.name); } } When I die everything resets and works fine. BUT there is just one object that is not reseting and continue in the scene. why ?
its either static or inside DDOL
DDOL ?
Dont Destroy On Load
So, i tried making a thing that lets me wall Jump if i collide with a Certain Gameobjects with the tag "Climbable Wall" But whenn i collide with it , not only does my character no longer have gravity effect it (not hitting the ground anymore) . It also reduces my JumpForce to below 1 when i spam space. U can see the values on the right side of my screen
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.
no i dont have that.. that is wierd.. well anyways that is not a bug i need to fix now.. not important.. but in the future for sure
yeah you would have to show the setup , which object you're talking about and what its doing instead.
yeah, its fine. In the future I wil address this prob again. thakn you !
goodluck 🙂
without seeing the full code do you have something setup that puts values back when you jump off ?
paste bin link
right below wit
um yeah I would not use OnCollider hit
its totally unreliable for what you want
You should either use triggers as a hack, or actually do Physics like raycast or other types of casts
yes, triggers can be used.. which is hacky way of doing it
or using Physics like raycasts and such
wiich are the standard for this type of stuff
I suggest you learn about them
one or the other or both?
One or the other is fine
any would do yes
just to get the concept
then use Boxcast or something more "thicc"
they're just for detecting whats there
distance but yeah
kinda
doesnt have to be a point, it can be a direction like boxcasts/spherecast
this seems like its cardinal directions toh
Can it move in all directions beyonnd cardinal directionns?
if you mean a vector you can make your own directions
that would be kinda useless if it was only NSWE
Bett
Does transform.something take the value of the current position of that object ?
For example transform.direction in a script for a game object would ONLY show THAT game objects direction?
well transform.direction isn't a thing, but yes. the transform property refers to the current instance's Transform component
I suppose I’ve found a lot of tutorials contrived. Difficult to follow. I was just wondering if anyone had a good recommendation of someone who knows how to explain things well
Weird the video showed him using that maybe I misread it
usually the documentation or official course
Documentation as in those things explaining each mechanic from Unity’s site? Yeah I do use those a lot. Just sucks to have to search each individual thing
Sorry I just have some issues studying by myself. But it’s good to know they’re good resources regardless
they're pretty good, some stuff is questionable and some poorly documented, but for most part better than most.
huh...Physx has Convex Cverlap but we can't do that In Unity ?
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/SceneQueries.html#overlaps
ig convex triggers but we can't do overlap or am I missing something..
Quick question, is it bad practice to save bits of useful code in a text file to reuse for other projects? I came across things like a camera locking script, a basic player movement script, things like that, but I couldn't possibly think of being able to remember them all
yeah its fine why not, imo its more neat if you make a custom package or something
or make your own libraries / dlls
reusing code is part of the gig 😛
@rich adderi tried usingn Raycast w/ this functionn detereminning whether i colide with the wall or not
Ray theRay = new Ray(transform.position, transform.TransformDirection(direction * rayCastRange));
Debug.DrawRay(transform.position, transform.TransformDirection(direction*rayCastRange));
if (Physics.Raycast(theRay, out RaycastHit hit, rayCastRange))
{
if (hit.collider.tag == "Climbable Wall")
{
collideWall = true;
}
else
{
collideWall = false;
}
}
```
same issue the player is stuck @ tht y level and never falls back down if it collides wwith a wal
my movement Script must be wrong
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.
this only changes the collideWall to false, if it hits another collider with No tag climable wall
it shuld also be included in the else of the main RayCast If
do like actually debug your bools and stuff when you add them 🤔
Line 75 i have 2 OR conditions idk if thats fuckingn it up
yeah i normally have a Debug.log with text
separate your methods instead of jamming everything inside Update
its hard to read this
Character Controller's built in isGrounded is also very unreliable
Unity's example?
ray is too thin tho
I couldnt evenn login much less use the learnn thing
i cant add that becuase its not letting me log inn
which IDK why
any idea what i can do?
not sure maybe ur using a vpn or something
not sure 🤷
did you refresh?
yes
ive tried it on multiple browsers with and without vpn
Disabled UBlock origin
still nothing
maybe clear cache/cookies

it wokred on my ipad
why is it broken on my pc
OK
So it was because of my VPN, evenn tho the connection was off
Debug.DrawRay(transform.position, transform.TransformDirection(downDirection*groundRayCastRange));
if (Physics.Raycast(isGrounded, out RaycastHit hitground, groundRayCastRange))
{
if (hitground.collider.tag == "Ground")
{
Debug.Log("Touching the Ground!");
isTouchingGround = true;
}
else if (hitground.collider.tag != "Ground")
{
isTouchingGround = false;
}
}
}``` How come it never reaches the elseif statement where hitground.
I have the bool as a public varaible so ican see if the check box ever gets unchecked
nvm
🤡
you don't need the else if condition. if the first if statement is false, then the tag is not ground. there is no need to check for the opoosite . . .
i figued it out
{
if (hitground.collider.tag == "Ground")
{
Debug.Log("Touching the Ground!");
isTouchingGround = true;
}
}
else
{
isTouchingGround = false;
}
solved tht
had to move the else
Now i jus need to figure out why my character doesnnt Move back down wwhen it collides wwith a "climbable wall"
im like 99% sure it has to do wwith this line of my code
{
jumpCount = 2;
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); // Reads movement keys (WASD).
moveDirection = transform.TransformDirection(moveDirection); // Turns the input into movement direction.
moveDirection *= isSprinting ? sprintSpeed : walkSpeed; // Chooses between walk or run speed.
}```
Hey guys. I have a problem here. What could be the cause that I am not being able to get the value from cs _finalBossOne._finalBOCurrentHealth it is always 10 as it is his health, but here I cant get it when he receive damage, only the default value. I have the variable on the boss set as public and inside my spawnManager, I have a method that is inside update, with this part to check if his HP is 0 cs if (_finalBossOne._finalBOCurrentHealth <= 0 && _canSpawnPoison){ _coroutinePoison = StartCoroutine(SpawnPoison(12)); _canSpawnPoison = false; } but it is always 10. I am using cs [SerializeField] private FinalBossOne _finalBossOne;and assigning the boss prefab in the inspector.
are you assigning the boss from the scene or a prefab in your project folder?
prefab in the folder
then you're affecting the prefab in the folder, not the one in the scene . . .
you need to assign the boss from the scene hierarchy into the slot . . .
but i have done like that many times and worked for other scenarios.. and in the scene I can only do it when it spawns.
this will change values on the prefab which has nothing to do with the scene or the game . . .
no, Instantiate creates a copy. you need to get a reference to the copy and change those values . . .
got it, will try thank you
ok Let me try to make the picture here and see what could it be now. I have this method inside the spawnManager ```cs
private void InvokeFinalBO(){
if (_player.playerLevel >= 1 && _canSpawnLastBO || Time.time >= 1200 && _canSpawnLastBO){
_camera.Follow = null;
_canSpawnLastBO = false;
_SpawnManager.gameObject.SetActive(false);
DestroyAllEnemies();
fBO = Instantiate(_finalBossOne, new Vector3(_player.transform.position.x + 5, _player.transform.position.y + 20.5f, 0), Quaternion.identity);
for (int i = 0; i < _spawnDelays.Length; i++){
_spawnDelays[i] = -1;
}
}
} ```here I instantiate the boss. What I tried now with what you said is I created a variable at the begining of the class as FinalBossOne fbo; this method is in update. and in update i put. ```cs
void Update(){
CoroutinesController();
InvokeFinalBO();
Debug.Log("BOSS HP: " + fBO.GetFBOHP());
}``` and gives me null reference.
debug log is after the method on invokefinalBo() in update
even tho I get nothing.
because now it is trying to get something that doesnt exist yet
what is the error line and message?
as it will spawn only when i get lvl 1.. so i cant have it like that
object reference not set to an instance of an object.. but might be because he will spawn only when I am level 1.
fBO (a lot of variable names are confusing because of abbreviation), is only assigned when the if statement is true. if it is false, fBO is not assigned and fBO.GetFBOHP will create a null reference error . . .
fbo, first boss one
I replaced a TMP Input Field GameObject and I'm not getting any Console errors. However running the game makes the editor crash inexplicably. Could someone check this out for me and let me know if it works on their end?
Is there a reason that my raycasts always return to the same point even though they were working before? i didn't touch the script or gameobject and it always sets the raycast point as the same random coordanites
well even doing that it gives me always 10
does it work if you remove the component? if so, add a new one and see if it still crashes . . .
After removing the object, it still crashes.
I have no idea why
I can revert changes on git so I'm safe but just very confused
it should because it was just instantiated (created). i'd expect it to have full health. add a line to remove health, before the log . . .
then the issue isn't the tmp component . . .
but when i hit the boss and he lose HP it should show no? i already have other bosses .. enemies always done like that but in this case here isnt working.. super wierd 😦
All I did was delete the legacy component and replace it with its TMP counterpart and now my game won't run
Perhaps something to do with that legacy object's components?
Hard to speculate without seeing code and your setup
possibly, i haven't used legacy stuff before . . . 🤷♀️
Could you try opening my project maybe? If it's not much of a hassle
It'll also test my GitHub setup as this is my first time using it
it should, but you'd have to place a log after the boss loses health for us to see. this snippet doesn't show that . . .
yeah I already put a debug log every where possible and it is always 10. this is messing with my mind hahaha.. done it so many times.. crazy stuff
what is this extra code after I implemented my interface? first time using them.
do I need it there?
Looks like it was auto-generated by your IDE
Yes, you need to implement every interface you use
Currently it will just throw exceptions to remind you to implement it
your IDE auto-generated that. when it adds required members from an interface, it places NotImplementedException to throw an error. this informs you that the requested method or operation is not implemented . . .
then you know to add the implementation . . .
ok thanks
not able to at the moment. i'm moving back-and-forth between cooking, discord, and figuring out my stat system right now. trying to figure out handling max value(s) for stats . . .
Yeah now worries, I'll try some stuff and see if it works itself out
it doesn't work at all anymore?
If anyone could try it out that would be fantastic though, just to see if the project actually builds
Hitting play just crashes it, no errors nothing, just straight closed
ouch . . .
{
if (rocketCooldownTimer > 0 || charges < 0)
{
yield break;
}
RaycastHit castHit;
Physics.Raycast(cam.transform.position, cam.transform.forward, out castHit, maxRocketDistance, whatIsRocketable);
if (castHit.collider == null)
{
rocketPos = cam.transform.position + cam.transform.forward * maxRocketDistance;
}
else
{
rocketPos = castHit.point;
}
Collider[] colliders = Physics.OverlapSphere(rocketPos, rocketExplosionRadius);
particlePos = rocketPos;
StartCoroutine(ParticlesPlay());
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddExplosionForce(rocketKnockback, rocketPos, rocketExplosionRadius, rocketKnockback / 1.5f, ForceMode.Impulse);
}
}
rocketCooldownTimer = rocketCooldown;
charges--;
yield break;
}```
This is the code
Hello, I have my project in Unity that consists of a player, with its corresponding movement script where within it I have an onGround bool to check if the player is jumping or not. I also have a camera that follows this player with its corresponding Script. I need the camera ONLY when the player jumps, not to alter its Y axis. Can anyone give me a hand?
also it works in some other scenes but not the older ones even if i updated the prefab
Why is this a coroutine?
You could just use a normal method and return instead of yield break
Also seems like you are using the "2D" way of doing raycasts. In 3D you can just do ```cs
if(Physics.Raycast(...))
{ ... }
else
{ ... }
instead of checking if the collider is null
@verbal dome can you help me pls?
Store your jump height in a variable when you jump
try not to ping specific people, you don't know how available they are to help (or if they even know how). someone will respond and help if they can . . .
And when your character is in a 'jumping' state, use that height for the camera's y position
Okey, sorry. Im new
yikes, never dealt with that before . . .
And I barely understand Unity as well...
But I need my camera to stay fixed on Y, if the player jumps
@keen galleon Additionally you can do so that the camera's y position is the minimum of it's normal position and the jump start height
I'm literally explaining you how to do it
Okay, I'm sorry, my English is not very good and I haven't been programming in C# for a while.
But I still don't know how to do that, can I give you my code?
So lets say you make a new float jumpStartPosY in your movement class.
Set that float to the character's transform.position.y when you jump.
You also need a way of knowing when the player is jumping or not. So set a bool jumping to true when you jump, and set it to false when you hit the ground.
Now in your camera script, if jumping is true, limit your camera's position.y to the jumpStartPosY with Mathf.Min.
It's trying to merge scene files but a regular merge tool won't be able to do it correctly due to Unity's YAML serialization. There is a tool you can use to do the merge but it requires a bit of set up. Unity has documentation for it here: https://docs.unity3d.com/Manual/SmartMerge.html
@keen galleon Mini tutorial here.
Amazing, thank you!
its still setting the rocket position to the same random spot on the map after pressing the button
I'm going to try to do it, see if I can do it. thank you
the weird thing is this happened before and fixed itself and then broke again without changing anything
Use Debug.DrawLine/Debug.DrawRay to visualize your raycast
I doubt that
Maybe it was always broken slightly
But now it shows more
@feral flax I'm trying to add the text
[merge]
tool = unityyamlmerge
[mergetool "unityyamlmerge"]
trustExitCode = false
cmd = '<path to UnityYAMLMerge>' merge -p "$BASE" "$REMOTE" "$LOCAL" "$MERGED"
To my .git or .gitconfig file as instructed. But I can't find either of those files in my project folder? Where are they normally contained?
Is it just this?
Its contents are:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[submodule]
active = .
[remote "origin"]
url = https://github.com/AdiZ-1579887/CipherDecoderApp.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
[lfs]
repositoryformatversion = 0
So I'm guessing that is where it's meant to be
theres nothing wrong when i draw the ray with gizmos using the same parameters it still goes from the camera and out the specified distance
.git will be a hidden folder so you might not be able to see it. It should be at the root of the workspace folder. .gitignore is usually in the same place as the .git but it could be in other locations as you can have as many as you like and they cascade. It's also possible you don't have a .gitignore if you never created one buit I assume you'd have a lot more issues if that was the case.
So the ray looks right? Your problem might be in the rocket's script, if it has one. Or whatever is moving it
I didn't know where to save my .gitignore file initially so it's just in the project's root. You're saying it should just be inside the .git folder?
Also I edited the config file and there is still a merge error. Do I need to do something?
The manual doesn't specify anything as far as I can see
Yes, it won't automatically fix anything because it hasn't been run. you need to run the merge tool on the file in conflict
So should I find the .exe in my Program Files?
You can make git use the tool by instructing it to use the mergetool in command line. You can do that with git mergetool [path_to_conflicted_file]
currently it is just a raycast and placing the explosion on the point where it hit
I do that from git bash, right? I have it installed but never used it as I've only used GitHub Desktop so far
yes, git bash would work
Great. Do I have to put the path in quotes?
I should just try it, sorry for asking so many questions haha
that's okay. It only needs quotes if the path has any spaces
but having quotes when you don't need them is fine
Cool. Somehow I can't paste the path, it's Ctrl + Shift + V, right?
not in git bash, unfortunately. I think it might be Shift + Ins
Oh no
Shift + Ins
Just right-clicked to check
Interesting choice. Thanks
But... I didn't use mergetooll?
weird, it looks like it thinks you made a typo somehow?
could be an invisible character from when you tried copy pasting
I have done everything you said and it doesn't work
But it definitely is a git repo
oh, also strange...
Right.. Show your code
What does the : .git at the end mean?
Is that significant?
it means it can't find the folder named .git which is where the repo part of the git repo would live on your hard drive
How is that? I'll show you my directories
It is essentially saying that the location you gave isn't set up as a git repo. Is it possible at all that you have the project in multiple places nad might have them mixed up? Otherwise, if the .git is there, I'm not sure why it can't find it.
I have written Osmal in the new thing that you told me to do
Definitely is a git repo as I cloned the repo straight to there..
@feral flax however I'm trying to resolve the conflict manually but there are no conflicts in the file. There were 2 conflicts showing in GDesktop, I fixed that, now there is one. However when I click Show in VSCode, the .unity file opens up and there are no conflicts
However there is this:
Which is the only <<<<<<< HEAD in the entire file.
It shows up twice?
wat
Which means it is the only conflict, correct?
just delete it
Tried that and the conflict doesn't disappear in GitHub Desktop
how are you even getting merge conflicts with your own personal repository
I should delete these three lines, correct?
It looks like that file was committed with a merge conflict and this is a conflict with that conflict
Tried reverting changes and somehow it did not work
Evidently
That's the only way to get two <<<<<<< HEAD lines in a row
Sounds about right
Should I try this?
Or just the HEAD lines?
Sorry but it's in spanish (?) and I'm not going to translate it all
Can you find any >>>>>> lines?
I'll translate it to English, wait.
yeah, incoming changes
Ok...
Can I just delete them?
All I care about right now is getting it working because I literally have 2 empty objects in my project - I'm not going to lose anything.
I don't see you setting saltando (is that jumping?) to true anywhere..
I can't say for sure since. If these are the only places where it's showing up it looks like it's okay to delete all the <<<<<<< >>>>>>> and ======= lines
First of all, should I delete those empty HEAD lines?
@keen galleon Come on, read my instructions very carefully before saying that it doesn't work. You aren't doing it right. Now youre just wasting my time
!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.
This is only possible because it looks like the conflict was from an insertion and nothing actually needed to be merged.
The real issue would be, if the file doesn't work after deleting those lines, that the first conflict that happened mangled the file. If that's the case then it'll be a fair bit more work to recover the file and changes and would need some git know-how.
@keen galleon Don't see you doing this anywhere
Oh dear
anim.SetBool("salto", true); // salto (Parametro del animator) = TRUE para que realice la animacion
enSuelo = false;
ReproducirSonidoSalto();
// OSMAL
saltando = true;
jumpStartPosY = transform.position.y;```
@feral flax I removed all that jazz and now GitHub Desktop allowed me to continue the merge
That's obviously a good sign, but does it void the possibility of that mangled file business?
Not until you can open it in Unity
You need to set it to true when jumping
Is this your jump method?
My scene came back! EVERYTHING IS FIXED
Andrew I would quite literally be so screwed without you
Great news, glad I could help, ahaha
Now I just have to figure out the bs issue that caused me to try and revert in the first place
yes
part of
The entire editor crashes when I try to run the project
Paste the whole script in a paste site !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.
So annoying because there are no errors or anything so I don't know what I have to do
Have you checked the editor logs?
@keen galleon And use english names or I can't help
Yep, the Console, you mean? Nothing there
Oh wait you mean actual logs
Where are they?
ah, there is a file that has the console log. It's handy because if Untiy crashes there is usually some logging that happens you can't see
Camera orbit: https://gdl.space/fivodawaso.cs MovePlayer: https://gdl.space/enurumemil.cs
But I don't see anything resembling a failure
Did you by chance open Unity again after the crash?
Yes multiple times
can you send the log that has prev in it?
when you open a new unity instance it overwrited the Editor.log with the new one, but it does keep the previous log around
The jumping in your camera script is not the same bool as the jumping in your player script.
You need to reference the player script from the camera script and get the bool from there.
Just having the same name doesn't magically make them the same value
This is weird
Couldn't extract exception string from exception of type StackOverflowException (another exception of class 'StackOverflowException' was thrown while processing the stack trace)
What even is StackOverflow? Never heard of that
How do I do that?
Sorry Osmal, I'm Spanish and it's hard for me to understand English.
Unity Inexplicably Crashing
Referencing objects from other scripts is something you should learn as soon as possible
i know this is a dumb question but Im getting confused can interfaces actually run functions themselves? or are they just blueprints for monobehaviors. Like I can't use this function in my interface because it destroys something?. Which makes me think im using this completely wrong.
they are just blueprints, no logic.
Is this inside the interface itself or the class that implements it?
Okay the newer C# versions have default interface support
Which you seem to be using
Destroy is a method in UnityEngine.Object and anything that inherits from it, such as MonoBehaviour
So you can try UnityEngine.Object.Destroy
Or just implement it in your monobehaviour
I keep forgetting that Destroy is a static method. 
Normally you can just write Destroy(...) if your script class is a MonoBehaviour but the interface is not
yeah, okay that does work. would it be possible to implement OnTriggerEnter in an interface?
maybe ill just do that in monobehaviors im still figuring out the best way to do this
Since you don't call OnTriggerEnter directly, I'm not sure why you would want to, but sure, in newer c#
Seems antithetical to the purpose of an interface
Hmm technically yes but it sounds a bit unusual
I really have a problem here and would love if someone would take the time to help me out.
ive googled it, but im curious what you personally use interfaces for? Would I be missing out significantly not to use them?
@verbal dome CameraOrbit: https://gdl.space/dugecawara.cs MovePlayer: https://gdl.space/oxacalaqoz.cs
doesnt work
They are useful when you want to have a reference to an object with specific functionality but don't want or need to know the specific implementation of the interface.
to limit access of a type through interfaces. you can only access the members of an interface instead of all members of a type . . .
and already refer to the objects and everything
I suppose that GetEnSuelo is now GetIsGrounded ? Because they have different names in those scripts
guess not, well first time after 3 weeks programming non stop i see something that really doesnt make sense for me.
@keen galleon I took a quick look, the new part of the code seems to be OK.
Next make sure that isGrounded is actually true when you are on the ground, and same with jumping when you are jumping.
You can use the inspector, Debug.Log or GUI.Label to debug the values.
try simplifying the approach. instantiate the boss using the prefab variable, remove some health, then log the value of the health. do all of this in one script and check the logs. comment out the other stuff . . .
i am 4h hours now creating all debug logs possible and trying all the ways possible. .but doesnt make sense.. anyways whatever.. i will try an ugly really ugly way to fix the problem.. its a lot of code for u guys to check and try to understand with me what is happening .. ty anyways
They are the same, only in the method of being on the ground in moving player it has been translated and in the method of the camera it has not been because he has left it literalç
@keen galleon I think the problem is herecs if (movementScript != null && movementScript.GetEnSuelo()) { jumping = false; }
Setting jumping to false in the camera script will not set it to false in the movement script
okay, I'll try it
The jumping in the camera script is a copy of the bool, not the same value
Just remove that code ^ from the camera script and move it into the movement script.
Just set jumping to false when isGrounded becomes true.
Read my latest messages first
okey
is it bad to instantiate inside an instantiate?
That would spawn two objects
Also that line is really unreadable lol
Don't be afraid to break it into multiple lines
thanks
(Ty guys for all the help its making a lot more sense now) Whats the point of making a health int in my interface? I can't set it in the inspector like with a monobehavior, what would I do with the health int?
Im attaching this interface to a monobehavior with a health variable already
You could draw a health bar after getting the Health value from the interface, for example.
The idea is that it's not tied to any specific class
I'm not great at explaining this lol
So how does the health stat on my monobehaviour interact with the Idamageable Health variable?
thats the part I dont get
The value in the monobehaviour is the value that is ultimately used
The interface just says 'hey I have a health variable'
That's the thing with interfaces, you can't have fields. get; set; in classes normally makes a hidden field, but in interfaces, that doesn't happen.
So you need to implement the Health getter and setter from the interface.
if(someObject.TryGetComponent(out IDamageable damageable))
{
DrawHealthBar(damageable);
}``` Simple example
You can explicitly implement it. Since I personally find it redundant to have multiple access to the Health value when referring to it as the type itself.
@verbal dome I have used Debug.Log on the player's movement, and when he jumps, the bool for being on the ground is set to false and the bool for jumping is set to true. I have also deleted the part of the camera code that you told me but it still doesn't work.
You can serialize the property of the monobehaviour like thiscs [field: SerializeField] int IDamageable.Health { get; set; }
It will show in the inspector
Did you do this in the movement script?
Don't skip steps
Well show your code again
am I misunderstanding how this works? why cant i use this variable?
I still don't see you setting jumping to false when you are grounded
What is the error?
all you really need to check is this . . .
FinalBossOne finalBossOne = Instantiate(_finalBossOne, new Vector3(_player.transform.position.x + 5, _player.transform.position.y 20.5f, 0), Quaternion.identity);
finalBossOne.ApplyDamage(5f); // Use your actual damage method.
Debug.Log($"Health: <color=cyan>{finalBossOne._finalBOCurrentHealth}</color>.");
Maybe you need to access it with IDamageable.Health but I'm not sure, I'm on an older C# version.
It's explicitly implemented.
You have to cast this to IHittable.
If you want to implicitly implement it, remove the IHittable part and add public.
interfaces don't have variables; you mean the property?
now yes: https://gdl.space/ipolurojuy.cs
you have IDamageable.Health, remove the IDamageable part . . .
still not working
Why didn't you do it before, I even asked twice and you said yes
As Lilac said, for abstraction.
- It's as close to multi-inheritence as there is in c#. You can have many interfaces that a class inherits from.
- You can also do things like TryGetComponent(out IInteractable interactable)
And many different classes could implement their own interaction methods. The calling class doesn't have to know what implementation is actually is, or what class implements it.
There are many other reasons to use it too
it has to, thats part of the interface implementation
because I've been dealing with this error all day and I'm already a little tired and desperate
sorry
Take a break and try again tomorrow
You read what I said?
You can also implicitly implement it.
nah, it is not mandatory . . .
i really dont understand what youre saying srry
Honestly it's really annoying trying to help and you just ignore some steps
Read everything 5 times before replying from now on
I need to measure the distance between the shot object and the target object frequently, but when I shoot, I create a new variable that can't be accessed in the void update, how do I measure the distance between these 2 objects while the shots are in the scene?
I've tried using "float distance = Vector2.Distance(temporary.transform.position, targetMiddle.transform.position);" but it's no use, since it's only executed once after the click, not continuously.
(Forgive me if I didn't make sense, it's confusing even for me LOL)
The compiler will automatically know that it implants the interface, that's pretty much it.
Implant lol
I need to deliver this project well done in two hours
Then you better pay some attention. Can't say much else
make distancia a class field instead of a local variable . . .
ok, but I already did everything you said and it still doesn't work
[field: SerializeField] public int Health { get; set; }
@true pasture compiler will know that you implement the interface implicitly IF the access is public and the name is the same.
Good luck, I don't have motivation to help you today, sorry
Most likely you did something differently again
I have passed you the code and you yourself can see that everything is as you have said. I have already told you that I am starting with this and that I do not understand English well. I do what I can
Sure, but you keep responding that you did everything I said and you really didn't
Just wasting my time
Might want to find a spanish speaking unity server if one exists
is this what you mean bc its not recognizing it
Well nothing, thanks for the help. If anyone else can help me I would appreciate it.
they do not exist
works in parts, the game only returns the value once, I need it to return it while the object is in the scene
show the EnemyMono class . . .
I'm asking here for a reason, it's my last option.
I forgot one more thing.
The member in the interface also has to be public.
Idk if you did.
Wait.
I meant in the class. @true pasture
The EnemyMono should have this.
Sorry.
Didn't clarified enough.
NGL, you could have right clicked the EnemyMono class and go to quick refactoring (I think) and you should have the Implement IDamageable.
And you have two options there.
i did it implemented it with the Idamageable.Health version
Explicitly, Implicitly.
ok
lemme check
okay now it works and I see what you mean by implicit or explicit
okay so now I can access the health of everything Idamageable without knowing what monobehaviour its on i think right?
The difference between explicit and implicit is pretty much you have to cast itself to the interface when it's explicit.
like thats the main benefit right?
Yep.
Different Mono behaviour can also use the same interface.
That's the abstraction part.
You shouldn't need to know the Monobehaviour itself.
Okay yeah the hard part was figuring out how to use the interface variables ty for the help!
This is the inspector for the camera. When you press play the money variable is set to 100 and I added the console log on SubtractMoney method and realized the method is never actually getting called. But I do not know why
or i guess soimeone said they arent variables but members
Well yeah, interfaces can't have variables or fields.
And getter and setter are secretly just methods.
based on your code, it will get the distance if atirou is true . . .
{ get; set; } are just sugar.
It basically means it makes a variable behind it automatically when used inside a class or struct.
start by remembering interfaces don't have variables, only properties, methods, events, and indexers. that is the main (and only part) confusing you . . .
Events?
you created a Health variable, not a property. that's why it didn't work . . .
Action OnAction;
Action<int> OnIntAction;
Still field aren't they?
nope, a field is just a class-level variable . . .
they're members . . .
any field, property, indexer, method, or event is called a class member . . .
So you're saying you DO see the debug in OnTriggerEnter that logs other.name though?
yes
Call getcomponent in start. Or better yet, just drag the object into a PlayerMoney field.
I can only think that the GetComponent call is causing issues?
It is getting TO the point where it would call SubtractMoney..
I don't really understand putting the getcomponent in start
The script is on the same object... there is no reason to call it EVERY time OnTriggerEnter is run
Just do it one time in the Start method and save it as a variable
public PlayerMoney money;
void Start() {
money = GetComponent<PlayerMoney>();
}
I'm having it on OnTriggerEnter because I want it to call the method every time a specific type of game object is clicked on. And I want to make different tags so that different objects send different values to be subtracted
That is not a good reason to have the getcomponent call in OnTriggerEnter
The way I suggested above means you can just do: money.SubtractMoney(amount);
That way you have the reference, it is saved, you can use it as many times as you want with any amount you want
I made the changes you suggested and it still picks up the object but still doesnt make it to the subtract method
Double click those logs and see where it takes you
this is what my code currently looks like
it takes me here
Ok, so your OnTriggerEnter method never runs
Go through this to find out why
https://unity.huh.how/physics-messages
Btw, this is why you should have more descriptive logs.
Like Debug.Log($"Trigger Collision with {other.name} by {gameObject.name}", gameObject);
If it's just the name, it is less clear where it's coming from.
You had three debugs (at least) ONLY showing a name.
So I realized that the objects im clicking and "picking up" still had a different script as a component and I am no longer using that other script. So I tried taking the code from it to put into my current scripts but now the gameobjects are not being destroyed and the subtract method is still not being called
I pay $5 to whoever solves this for me. Hello, I have my project in Unity that consists of a player, with its corresponding movement script where within it I have an onGround bool to check if the player is jumping or not. I also have a camera that follows this player with its corresponding Script. I need the camera ONLY when the player jumps, not to alter its Y axis. Can anyone give me a hand?
camera.transform.position = new Vector2(player.transform.position, camera.transform.position.y, `camera.transform.position.z)
can change depending on your game
Did you go through that link?
Do you have a rigidbody or character controller on one of the objects? Colliders on both with isTrigger selected on one?
I did. I have a box collider 2d
look md
md?
private message
On BOTH objects (including the camera?)
And one being a trigger?
And what about the rigidbody or character controller?
I don't have it on the camera but I do have it set as the trigger
Well that is why it doesn't work
The object with the script needs a collider.
And AGAIN, what about a character controller or rigidbody?
You're not being very clear
I have never used either of those so I'm not familiar with what they do
You need one on either of the colliding objects for OnTriggerEnter to register.
In short, you are missing a lot
This is why it isn't working
CharacterController is a built-in movement controller
Rigidbody is a component for physics/movement
Are you moving your player with the transform?
You may want to just manually do spatial queries on your own like OverlapCircle
No I am not, I don't have a player. I just want the player to click on objects and have a counter deincrement
Clicking would usually be done with a raycast or something like that.
What is the OnTriggerEnter supposed to do if you aren't even moving?
OnTriggerEnter is for physics collisions
This is essentially a very bare bones shop function. The player mouse clicks on a still object, and a text UI component with a value subtracts the "value" (int) from their total
No, I understand
I'm saying OnTriggerEnter is not the right thing to use here
Scrap it. Use a raycast
Or OnMouseOver or something
getcomponent takes more resources so better to call few times
It's actually very cheap (even when it fails, which is comparatively much more costly), but it's always best to do less whenever possible.
its not expensive but it is best to minimize yeah
Should I just move all my stats to an interface?
or would that cause a problem? I can't think of one.
Interfaces can't have fields.
yeah i know
You could probably have a struct with those as it's contents - they're all value types.
even better, create a Stat class and have a list or dictionary of Stats . . .
An interface could work and you can just pass the class ref as the interface without exposing the whole script.
depends how you want to calculate it though. On the actual enemy class or some other utility class for all that.
For what purpose? Does some script need to know max health to pass damage to the IDamageable interface? What about Attack? BounceOff?
If it makes sense then sure.
To me, I feel like IDamageable should have a ReceiveDamage(float amount) method
Maybe with an enum for damage type.
yeah, that makes more sense to me . . .

