#💻┃code-beginner
1 messages · Page 149 of 1
looks like its grabbing the first collider.. and if ur happening to be overlapping (2) of em.. it just gets the first one and ignores the 2nd
maybe they are overlapping or something
nothing that i would think would help ya out.. just the basic stuff
I'd love if someone explain me what are Interfaces in C# for
Ive watched some youtube videos about this but still dont get it
a simple way to "enforce" other scripts to implement a certain method/prop
It is a way to basically say "I don't know anything about this object, what type it is, what it does, but I can 100% guarantee it has these functions that take these parameters"
So, if you really don't care what an object does when it gets shot (Is it a crate that breaks? An enemy that dies? A target that opens up a locked door?) you can have an IShootable interface on all of them and your bullet can just say "Please call your GetShot() method, whatever it is"
So is it just a thing with methods/variables that you cant give behaviour to, but you can add the interface, and give these methods/variables inside a behaviour that you want?
IClickable with a CLick() method for example... it can be a NPC it could be the player, or a pickup.. each script would use the IClickable interface.. so each script would need the Click() method for it to compile.. so now u can call Click() on anything u click and the script will handle w/e it does..
interfaces dont have any behaviors, how they are implemented are unique to each class that implements interface method
that way ur click script that does the clicking doesnt need to do a check each time to find out what type of script ur clicking on
And you just put your behaviours into the implemented interface methods?
yeah each script handles it differently
yessir
but they all have the same method
It's a thing that defines methods and properties, but doesn't implement them. You can make any other class implement that interface, and the compiler will force you to add those methods/properties to that object, and an instance of any object that implements that interface can be stored in that variable.
Using the example above, you'd have classes with type lines that look like this:
public class BreakableCrate : MonoBehaviour, IShootable
public class Enemy : MonoBehaviour, IShootable
public class Target : MonoBehaviour, IShootable
And your bullet could simply do:
other.GetComponent<IShootable>().GetShot();
and it'll get whichever MonoBehaviour on that object implements IShootable
Whats the prupose if you can just make these methods in the script yourself
to share commonality when you don't care about a particular script
its so when u click u dont have to do 10 different checks to find out what kind of Method ur calling..
Without interfaces, your bullet would need to do this:
if (other.TryGetComponent(out BreakableCrate crate) {
crate.GetShot();
} else if (other.TryGetComponent(out Enemy enemy) {
enemy.GetShot();
} else if (other.TryGetComponent(out Target target) {
target.GetShot();
}
^ to avoid that exactly
And any time you added a new shootable thing you'd need to go change this function
exactly you would have a huge mess of if checks
If you use interfaces, you can add in a new script:
public class Balloon : MonoBehaviour, IShootable
and it instantly works with the bullet, no other changes needed
if(confirmedHit)
{
if(!shiftModifier)
{
if(hit.collider.TryGetComponent(out Unit_RX orderRx))
{
SelectUnit(orderRx);
}
if(hit.collider.TryGetComponent(out Selectable selectedTarget))
{
Select_WorldObject(selectedTarget);
}
Debug.Log("Normal Click");
}
else
{
Debug.Log("Shift + Click");
if(hit.collider.TryGetComponent(out Selectable selectedTarget))
{
//HandleSelectedTarget(selectedTarget);
}
else
{
HandleUnselectable(hit.collider,hit.point);
}
}
}``` heres an example of my script that imma be changing over to interfaces
no need for a big ass nasty if else chain. esp when i start adding more and more selectable objects
Did you save the input asset and make sure "generate C#" is checked?
OHH So with interfaces you just do the InterfaceMethod(classHere); instead of this all?
no
u dont even have to tell it what class..
With the interface, it's just:
other.GetComponent<IShootable>().GetShot()
all it knows is if its an Interface of that type.. it calls the method regardless
each method would be written to do different things in each script that uses that interface
If you try to use Look, do you get any errors in Unity, or just the IDE? It might need to have the project files regenerated to realize the input asset changed
Ohhhhh I think I got it
If I have a function I want to run every 5 seconds, not every frame, how can I slow that down?
use coroutine
With yield seconds?
Thanks
And I can put that in Update?
no you don't need update at all
No you put it in a coroutine
it's just the IDE
no errors in unity
Yeah, try regenerating project files
Btw the difference between get axis raw and the new way is too big
I mean, is this the equivalent of getaxisraw
But how do I make it run forever? That ends after 5 seconds. Do I put a while loop inside it?
yes
https://hatebin.com/thcuqpgtku
an example usage.. Interface at the top, two different scripts that use the interface in the middle.. and on the bottom how a script would determine if its an interface and call the Method of it, edit: as long as it find a script that uses the interface you know u can call the Method... b/c all the classes using it MUST have that function in order to be properly implemented
That worked thank you so much!
Tysm
im tryna make an inventory but need a design where can i make it
where can i do it tho
in the code
what do you mean where?
cant i just use sprites or smth
you can use sprites, text, or pixels.. or anything else u want
wat?
i got a question
to interpret visual scripting ,unity automatically builds .cs files right ?
start browsing for tutroials.. or examples on youtube or github.
like shader graph builds shader assets
find one thats already built on the asset store.. and reverse engineer it
you code inside an IDE (Visual Studio Community) (VS Code) (Notepad)
an inventory would be a mix of Graphical elements.. and code
I know this is technically unrelated to coding since im going to talk about visual scripting, but I got a friend that loses ALL created variables when building (out of the project folder ofc)
what could be the reason ? it happened multiple times
if the answer is yes then asking here can be the good place
All the assemblies are located in /GAME NAME_Data/Managed/```
mh
it isn't technically .cs files after you build
but does is go through the process of creating cs files before compiling ?
i asked the question on the VS server in case, maybe someones knows for sure
idk how unity can remove variables from grpah assets when building
ty for the answers guys
for anyone wondering :
No, it's a reflection based interpreter.
tell ur friend to rip the bandaid off and start coding in csharp
in the long run, they'll not regret it
Actually CS does not compile to machine code. It compiles to IL which is interpreted into machine code at runtime, that is what makes it possible to be multi platform
ive seen that before whats IL abbreviation?
Intermediate Language I believe
Intermediate lang
IL Intermediate Language
transform.position.y = cameraGameOBject.transform.position.y;
``` doing this gives me the error Cannot modify the return value of 'Transform.position' because it is not a variable
yes you cannot directly change a prop in v3
u cant directly modify the transform's individual properties
oh ok
You cannot both get and set an individual component of position in the same line. You'd need to store the current position in a Vector3 variable, modify the vector, then set it back
copy the entire value, edit that and plug it back in 👍
ig ill just make a new vector 3
we need some slash commands for vertx's page 😄
the deadline is to close for him to restart unfortunately
no worries everyday i tell him chsarp is better :)
always with a deadline lol
well, they might require him to do it in visual scripting
iono, but i dont trust visual scripting at all. u kinda confirmed it better for me
since its Game Design they dont have time to make us learn coding
so most people that never programmed or to lazy to learn goes with UVS
lucky i already did a lot of lua, py and php so learning csharp wasnt that hard for my game project scope
it was more about learning how unity works
ya, that makes sense.. if i were to chose tho i'd pick a very small project im able to complete (even with little scripting knowledge) than a bigger one that i end up not finishing with visual scripting (which seems easier from the outside looking in)
before learnign unity, i was using blueprints in UE for 1 year and a half
and damn that UE did a good damn job with VS
i first tried unity VS but it was horible
if you say so
cmon i dont see any issues 
VS code cant be more easily messy than other languages
but csharp can still be a bunch of code written evrywhere with no logic
lol. atleast you can use keywords and the find function to help..
eh as long as you can get the job done, doesn't matter what you use
ya, in my opinion tho its easier to get into a good work flow.. with structure when learning to hard code
in visual scripting ur just moving around nodes to make them look pretty
ive seen a youtuber that coded on his telephone..
so ur correct @rich adder the tools are irrelevant.. (in a sense)
yeah VS doesnt help you to get well structured
you can hammer a nail into the wall with a screwdriver if u want..
it'll eventually go in
yeah you'd be surprised how many diff successful indies just use visual scripting or maybe drag n drop like Game Maker
gotta give respect where respect is due
this is a kinda well sorted graph for me
like regular code each people got their manners
ya, thats pretty normal
still looks horrible but ig depends what you're used to reading
you can group the nodes together too to make it even better
yeah im to used to xD
this was before making it more readable
wdym
u can encapsulate nodes into a group
and clean it up a lot
what are they. Macros i think they call em
yeah ik
let me open my project
damn its been more than half a year i didnt do UE
Unity takes all my time :(
ya, i thought i was going to swap to unreal.. but came right back to unity..
unreal is pretty but unity to me is easier and more powerful
im still team UE
but Unity is really decent
thought it was trash tbh ...
didnt dig much of it before trying to dev
well if ur in the UE echo-chamber.. thats probably what id expect
each of those grpah are like aroudn this size
ya, thats better.. thats the only way i can use visual scripting.. is to use different colors and groupings
otherwise i get super lost
pretty spaghetti
yeah #region isnt enough
gotta use Headers too
i always try to make readable inspectors when needed
pretty tidy inspector
do u always make ur floats and integers into sliders like that
can anyone help me everytime i start game my player just starts floating away
ask yourself, could I help someone based solely on the information I have just provided?
my bad hahah srry so i dont know what the problem could be i think it will be something in my code or is it something in the unity player settings i dont know but when i start game the player object just starts slowely floading away i can provide my code if u want
this is a code channel, so what do you think?
https://hatebin.com/lmbcoogvim this is the code
what? everything looks fine what is this?
First thing you need to do is fix your logic, you have a lot of bools there that you are setting to true but you never set any of them back to false
Is there a way to reset Coroutines? In my code I start a coroutine and then part way through it I stop it in a different part of the script. Instead of stopping it I want to stop it and have it reset so the next time I call StartCoroutine it plays from the beginning.
okay thank you I will chnage it
show the stack trace
StartCoroutine always starts from the beginning
there is no "Reset" Coroutine
I thought stoping a coroutine stops it where its at and then start plays it from there
Mb
how are you stopping your coroutine?
a what now?
StopCoroutine stops the whole coroutine
Coroutine cor = StartCoroutine(MyMethod());
...
StopCoroutine(cor);
I suspect you are not stopping correctly
oh shit
i just realised what it is
its not that but its similar
i was using gameobject.getcomponent for a component that didn't exist
🤦
So for me my C# Intellicode extension is not working for programming in Unity , I have vs code and like it doesn't recommend other commands for me and doesn't show any information at all. I have been using vs code like that and it's quite stressing
!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
Follow the VSCode configuration linked above ^
Unity extension now exists also it installs new devkit
I am trying to get unity set up for VR use. I am trying to follow the prerequisites guide from the documentation: https://docs.unity3d.com/2023.3/Documentation/Manual/xr-configure-providers.html
When I install XR Plug-in Management, I am supposed to see a section titled XR Plug-in Management with a list of Plug-in providers below.
Instead, this is what I see:
Google does not have any pages that include the exact phrase "does not have any associated build rules"
can you use onCollisionStay instead of raycasting for ground checking or is it a bad idea because i havent seen anyone do that
why would you want to? if you use Collisions for ground checking what benefit would it be over CollisionEnter and CollisionExit?
the raycast is better
im trying to find alternative to raycast because i cant figure out how to handle slopes
wdym "handle slopes" how would raycast not do anything oncollisionstay can
Then you should ask how to handle slopes. You should use one of the shape casts for this. The platform being slopped means that the ground directly under the player is further away. You also dont want to fine tune the raycast distance
i thought oncolissionstay would be more precise and i wouldnt have to adjust raycast lenght
ill try it thx
You could make it work but you will run into weird edge cases. Like with a rigidbody slightly bumping up and then not being grounded when they only moved like 0.001 units upwards
CollisionStay is never a good solution for ground check
Got any compile errors right now?
Freshly installed packages won't work properly until Unity manages to compile. That could be what's causing that
I decided to start from scratch with their default VR template. Things are working now, I'm not sure if it's because I also switched back to the last LTS build or something else but I'm not questioning it rn
Thanks for the help though fen
hey guys is it still worth it to learn unity after the decisions made about the pricing or whatever
i didnt read too much about it yet but decided to ask here to just understand it better
You should read more about it
this is a code channel so not the place to discuss it. but only you can decide that
oh sorry about that but can you elaborate more, who does the decision hurt the most? solo devs? hobbyist? companies?
go do your own research. #archived-pricing-updates-talk
ok thanks
At the end of the day, the chances of it ever affecting you are as close to zero as it is possible to get
lol, i be wishing it'd affect me ;D
Sorry to disappoint, ain't gonna happen
i'll be sure to still send ya a key when its gone viral and all the streamers are playing 😛
Do that and I'll be the first to congratulate you
Hi, I have a question. I have seen some GTA style overhead camera transition (I hope you understand) and I was wondering if it may be possible to like have some sort of script to automate it; I think unreal has something like camera cutscene idk. Or do I just have to hardcode the animation. I was just curious, thanks
epic! lol ill expect a biased review to boost my exposure
Timeline?
^ this.. its just an animation and a camera
cinemachine would also be helpful..
has dollys, and tracking, and stuff
Hmm, possibly what I need, but I do need to hard code every animation, correct?
no, the timeline is a component/ a Graphical panel
what?
Is it like a ui tool to make animations easier, is that what you are saying?
alr, nah i was wondering if there was something like you just like pre record a "template" and then all you change is the target location
im trying to make something very quick you see
Create your own Unity short film:
https://courses.obalfaqih.com/courses/unity-filmmaking-101
Animation Track | Getting Started with Timeline (Unity)
Need help? Book a consultation session now:
https://store.obalfaqih.com/products/unity-consultation-session
This is the second tutorial about Timeline, and it's about the Animation Track.
We'll go t...
if u want quick id use Cinemachine.. and some Cameras..
with cinemachine u can just toggle different camera's and it'll automatically transition between them
really? But if I had a basic character controller, surely that would get messde up
could make a cinemachine camera with its own animation.. and just toggle the main camera off and the new camera.. it'll automatically transition to that camera.. and then could be animated.. u could swap back to the main camera when its finished
Cinemachine and Character Controller should have nothing to do with each other
not really.. u can just disable the camera u use for the player.. and it'll transition to the next one.. w/e one u enable..
can then just disable ur movement script stuff until u go back to it
if i want to use a Tilemap Renderer component in a script, how do i do that? do i need to use additional stuff except the System.Collections, System.Collections.Generic and UnityEngine?
or do i simply use it like a Sprite renderer instead?
Tilemap stuff should be inside the default UnityEngine;
huh i think for me just making something really simple like just a simple coroutine in my camera controller with some lerps should do the trick actually probably i guess. thanks though! I'll definetily look into that
always check the docs
https://docs.unity3d.com/ScriptReference/Tilemaps.TilemapRenderer.html
class in UnityEngine.Tilemaps
- System.Collections is usually used for
Coroutines - System.Collections.Generic is usually used for
<Lists>
Tilemaps is in UnityEngine.Tilemaps namespace
on top of this, a properly configured IDE should show the correct namespace in the suggestions and can import it with the quick actions if it wasn't imported automatically
Assets\Scripts\Player\PlayerController.cs(81,27): error CS1061: 'TypeWrite' does not contain a definition for 'last_text' and no accessible extension method 'last_text' accepting a first argument of type 'TypeWrite' could be found (are you missing a using directive or an assembly reference?)
Show !code for TypeWrite
📃 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.
start by configuring your !IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
It really is super simple to use cinemachine. It actually uses the same camera.
A cinemachine camera is just basically like a placeholder for the camera..
Its just 1 component and you can set the priorities of the camera..
You can disable and enable camera's and it automatically just works.. or you can change the priorities and the camera will
go to the cinemachine camera with the highest priority..
there's no code in typewrite that is relevant
i'm trying to access the variable
inside of typewrite
That is literally the only thing that is relevant
Show the full class that is contained in
be prepared for a mess
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Well, before we gett too far into the weeds: Have you saved
{
FreeLook = GameObject.FindGameObjectWithTag("Free Look");
if (FreeLook)
{
FreeLook.SetActive(false);
}
player = GameObject.FindGameObjectWithTag("Player");
if (player)
{
player.SetActive(false);
}
}``` is this the best way to pause stuff?
ignore the player one. the free look is cinemachine
🤦♂️
thank you 🤣
- You should not be using
Finds like this, you should cache those references once - Disabling an object is a bad way to pause it, anything that references it still runs, it'll run any OnEnable/OnDisable logic, and any non-Unity methods will still be working as normal. The best way to pause something is to have some sort of singleton "PauseManager" object that anything that's pausable can read from and handle itself being paused in its own way
quick question
is there a way to have a sprite inside of a TMP text object
like "Do X for 10 🪙"
the coin being the sprite of a coin
yup, a singleton to pause is a good call
So when you say cache get its last xyz and set player to zero. then on enable reset them values is that what you mean?
When I say cache I mean store the reference don't use Find every time
get the reference once and reuse it
does it really even need to be a singleton rather than just a static class? what benefit does it have from having an actual instance
player = GameObject.FindGameObjectWithTag("Player");
the player isnt gonna change probably.. u can cache the player as soon as the script first runs..
then just call that reference any other time you need it..
player.DoSomething()
probably not. its going to be a core mechanic so its just there to get the ball rolling
i was thinking that it could just be a simple static class.. as thats all it does.. cs void Update() { if(Input.GetKeyDown(KeyCode.Space)) { gameIsPaused = !gameIsPaused; PauseGame(); } } as this is all it does
When you say cache this is where i get lost. are you saying get cache in the player script becuase i have access to it. And not on a Game menu script using the find.
no hes saying dont get the same reference that it'll always be every single time you pause the game
I am saying cache the references instead of using Find over and over to re-get the same references
private void Awake()
{
freeLook = GameObject.FindGameObjectWithTag("Free Look");
player = GameObject.FindGameObjectWithTag("Player");
}
private void Pause()
{
if (freeLook)
{
freeLook.SetActive(false);
}
if (player)
{
player.SetActive(false);
}
}```
ah,well if you need an Update method then it would need to be an instance. i personally prefer not getting input directly in my manager classes like that but instead of other objects that get input and dispatch it to other objects like my managers
like why would you ever need to grab the gameobjects other than once?
even if the position has changed.. the gameobject has not..
player.transform.position would still be updated to the new position of that guy.. when that function asks for it
oh i see. sorry i was reading this as dont ever use find game object
sorry guys
peeny dropped
many thanks
I mean, basically
you shouldn't unless u need to
find has to go thru the entire project
or the heirarchy atleast
yes. thanks for your help.
one more thing that just popped int omy head. if this script was dont destroy on load and the player was. and im using on awake to find the object. Would awake be called again. and would i have to change script order to make sure the player Instantiated game object is being loaded first?
Awake would not be called again
It is called one time in the objects life
So would that then lose a cached ref to the player?
Unless the Player is also in DDOL, yes
player is never in any of my scenes he is being cloned
I dunno what this script is, but maybe the Player could reference it and register themselves in Start?
Oh, like a PauseManager?
{
// Check if player, camera, and Cinemachine already exist in the scene
if (GameObject.FindGameObjectWithTag("Player") == null)
{
Instantiate(playerPrefab);
}
if (GameObject.FindGameObjectWithTag("FreeLook") == null)
{
Instantiate(CinemachineFreeLook);
}
// Ensure that this GameObject persists across scene changes
DontDestroyOnLoad(gameObject);
}```
I would consider a static accessor
this is my ddol
If you're instantiating it there, why not just cache the returned instance and check for null instead?
To be clear, you are wanting to switch scenes and do this check then?
Do you mean make this a singleton?
Not sure what a singleton is supposed to do with what they said?
Did you mean to respond to me saying static accessor?
Otherwise, no, caesar did not mean make it a singleton
so I have an inventory and on each inventory slot i have a script that will send an event when an item is dropped on it (to signal to modify the actual inventory along with the ui) How can I get a reference to that event on my scriptable object inventory which holds the logic?
like what is the best way to do it
i was replying to casar then,. I was just asking if it ran awake again but you answered my question. thanks
I didn't read everything but if you basically want to re-spawn the player on scene change then use OnEnable()
If I remember correctly DDOLs get disabled and re-enabled on scene change
for some reason it can't move beyond this point when I press D?? I have no idea why
I also have no idea why
Without seeing any code or the objects in the scene and how your player moves how should anyone know?
yo, i need code for damage popup text
Provide more detials
Yh Im just taking ss's one sec
If anyone has a ready code that would be very helpful
thanks
Find a tutorial then
if (damage){
PopUpText();
}
XD
Is it ok to nest actions?

I've disabled everything new that I added before it was broken
And in the actual scene its genuinely just tiles, haven't added any fancy effects to them or anything
yo ive always wanted to try and make this but im not sure the name of it, basically my character keeps bumping just below the edge of a platforms box collider and i want them to just get on top of that since they would have barely missed the edge is there like a name to this mechanic that i could look up or some kind of way to make it
ive heard of edge bumping but that doesnt seem to lead to anywhere
@modest dust @wintry quarry nvm I think I figured it out
do either of y'all know how to make the camera stop defaulting to the new camera that I've added?
I just want it to stick to the main
does anyone have a good source to learn about an event system?
Maybe named step height?
Is there a way that I could FindObjectOfType and output the variable all in one if statement? It would be similar to TryGetComponent out var
So i encounted a problem because my camera and player are being instatiated on awake in another script when i use private void Awake() { freeLookCamera = GameObject.FindGameObjectWithTag("FreeLook").GetComponent<CinemachineFreeLook>(); player = GameObject.FindGameObjectWithTag("Player"); } in another script i get NullReferenceException. if i put it inside start it works. Will this be safe in start. all the script does or is going to do is bring up a save menu.
Create your own extension method
As long as you follow the "initialize yourself in Awake, get references from others in Start", there will be no issues
{
}```
Its only for testing purposes but how does this look?
you wouldnt recommend using Script Execution Order and make my DDOL come before my GameMenu script?
Will throw if it did not find a matching object, so: bad
No. It'd be TryFindObject...
i use custom script execution order for just a couple of things that I know must go before/after everything else
All enabled cameras will render all the time. Drawing order is determined by camera depth
I recommend using Cinemachine instead of multiple Unity cameras if you just want multiple camera angles
Ok thanks I'll look into it
is it possible to code an object to go in a patrol way and if it sees a player, it runs towards it and when the player is off the object's tracking system, it goes back to normal patrol mode?
Im only using 2 cameras one for battle and onefor free roam
if so, what function would I need to use?
You can code literally anything you want. Nothing is impossible
luckily I fixed my issue by going so far back that it stopped and carefully adding what I wanted to add
Many functions. You will need to write a whole state machine
so i have a type writer effect, and I want to be able to skip specific keywords that won't be typed letter by letter, but I don't know how to go about this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
specifically because the sprite won't show up until it is done typing
You could try checking the character before printing it, and if it's <, keep looping over the string until you find a > or the end of the string, then add that to the display text for this iteration of the coroutine
Assuming it's just those rich text tags you want to be parsing like that
yea that probably will be my only use case, thanks i will try doing that
hi, I was wondering what do I have to google to understand how to use these static animation images that came with a free game kit i downloaded
do i have to turn them into a sprite sheet?
this is a code channel. but if it did not come with animated prefabs or animation clips or anything like that then yes, you'll need to set up the animation(s) manually yourself
ah okay, sorry. i wasn't sure if it was done through code (like looping thru the images) or not.. since the images are already there do i just skip to this part in the unity tutorial?
That would be step 6, not 7. But I'd follow the entire thing if I were you, so you know what to do if one day you receive one sprite sheet and need to slice it yourself
ah okay just making sure i'm on the right one. i'll follow the whole thing like you suggested for a better overall understanding 🙂
hey guys. any idea why the rotation is like this when opened/closed? its supposed to be 90 and 0
https://hastebin.skyra.pw/waretefusu.csharp
If you want to change how the door is oriented with a rotation of zero, parent it to an empty object and rotate the parent to compensate.
Also, you should be using local rotations, not global
so do i just replace every transform.rot with transform.localEulerAngles?
what you're seeing in the inspector is the local rotation of the door
this may differ from the world rotation of the door if it's parented to something
but yes, if you use localEulerAngles, you'll (probably) see the same value in the inspector
you can still get different numbers out, since those Euler angles will be turned into a Quaternion, and then turned back into Euler angles to display in the inspector
That would certainly be more correct (as opposed to incorrect lol), and may work fine if the door only rotates on that one axis. But it's generally best to track and apply your own euler angles if you can instead of reading from the transform.
Hi ive got two cams one on a render texture and one showing the screen how canimakethe UI panel show only on the one in the render texture
i got it working, but do you know if this method could bring any problems or if there are more efficient ways of doing it
for(int i = 0; i < writer.Length; i++)
{
if(writer[i].ToString() == "<")
{
Debug.Log("Detected");
for(int d = i; writer[d].ToString() != ">"; d++)
{
caught_text += writer[d];
i = d + 2;
}
tmpProText.text += caught_text += ">";
}
tmpProText.text += writer[i];
yield return new WaitForSeconds(timeBtwChars);
}```
stringbuilder if caught_text is getting +='d a lot.
but 99% time prob worth worrying more about like polys, texture, lighting, etc.
define a lot
caught text would only be +='d when it catches a sprite in the text
Also prefer comparisons to character literals, instead of converting them to strings
if (writer[i].ToString() == "<") // meh
if (writer[i] == '<') // better - notice single quotes to make a character literal
Christ I'm so bad at references objects
i did not know that's how you do it, thank you
id say stress test it, make ya some buttons that would trigger it how u would actually in the game. and spam it, try changing it, etc..
should let ya know if it'll be sufficient for ya
alr, also, just saying that is a pretty cool dialogue box lol
thanks, after i got the text writer working it was easy enough to add a panel, and just pass the string to the writer
are you trying to reference a script or gameobject
or better question
is "Sun" an object or script
both which is stupid but I want to reference the object so I can get its position
well one i would make different names for the script and the object
Ye i had that until 2 seconds ago because i thought i finally figured it out :v
u put the sun gameobject in there..
u can just call newPosition = Sun.transfrom.position;
not sure why ud want to grab the sun component each time ur trying to build that vector
thats this right
yea, but ur referencing a class called Sun
so that object must have a Sun.cs component on it
it does
otherwise id just use a gameobject reference..
public GameObject theSun;
yea, then u can just slot ur sun gameobject in there.. and in the script calling Sun.transform.position will get the transform of the gameobject.. that has the Sun
(the one u referenced in teh inspector)
But it comes up with type mismatch
b/c u didnt add the transform
quick question, what would adding parentheses in a line like this do?
rb.AddForce(0, knockbackUp, (playerOpposite.y) * knockbackForward, ForceMode.Impulse);
why would it be a type mismatch? what part of code says that
order of operations..
When i try to drag the object into the reference part, the box says type mismatch
thank you
a + b + c is not the same as (a + b) + c
needed to make sure
is sun on the SAME gameobject..
or a child of that gameobject?
that was smooth
You are trying to get the Sun component from itself
Oh, wait, that was quite a scroll down I didn't do
im struggling to figure out a calculation that can get the opposite direction of another object's y rotation. For example, im trying to make the enemy that gets hit by the player's sword attack be knocked backwards based on the player's y rotation, but for some reason it gets knocked back the same direction regardless of player rotation. Any ideas?
if u have a rotation u can just add 180 degree's to it and that'll be the opposite rotation
oh thats a much better idea than what i had
or if u have a direction u can just negate it -direction
and that'd be the opposite way
i tried that and it didn't work
why not just use the player's transform.forward and optionally project it on a plane represented by the ground's normal
Were you dealing with a rotation or a direction
playerOpposite.Normalize();```
this is what i tried just now but i realise it wouldn't work
welp, the 180 degree turn is always a win
the enemy gets knocked back in a direction based on the player's rotation
That is getting half the players rotation in degrees. Makes sense that it wasn't giving you good results because that doesn't really make sense
yeah it made sense in my head
tried that too
show that attempt because using the player's forward is better than manually adding to its rotation and is already a direction
yea im thinking both of those solutions would be adequate
probably just some misplaced mathmatics
oh wait im stupid
if ur facing forward its technically a rotation of 0
0 * anything would make it a non-existent force
how come its not like -180 or something
when the player approaches the enemy
Why are you using rotation now? https://unity.huh.how/quaternions/members
idk man im dumb
lol, no worries, rotations and quaternions are always a bit of a challenge for beginners
overthinking it sounds like
the usual suspect
Is there a way I can get a variable from one scene and use it in another one? If anyone can explain or link a good video to me?
data persistance
the easiest to start with
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
so that worked well, i also found out i needed to move it on the x axis too because it would only do the knockback forwards and backwards otherwise
Ty 🙂
Just tryna get a timer to save the final time and display it on a credit screen 😅
You can also use a singleton static instance but thats prob more to learn
Yeee I'm just tryna do a game for my A-level project, whilst this bit doesn't qualify as complex enough I'm trying to eventually save those times in reference to a login of sorts . So I'm just trying to work my way up 😂
Saving to PlayerPrefs is baby steps to doing cloud/server saves
UnityCloudSave for example lets you save similiarly . All it is Key-Value save
When you say that do you mean its really simple?
super simple
Damn, outputting the data as a graph? Would that be able to make it more complex
not really
that'd be scripting that calculates and draws after u retrieve the data
the playerprefs save and load would still be the exact same
I'm just tryna get some complexity in the project 😅
well, why not have it track ur new time vs the last time u tried..
give a breakdown afterwards telling the player if they did better or worse
Ohhh that's what I meant by graphing
Like over time it saves their attempts and compares them
that might be too complex for player prefs
ud probably want to serialize a list or something to track attempts.. and have it dynamic to be able to register a single attempt or as many as the player plays
Ahhh alr
but then again idk.. playerprefs is supposed to be short and sweet.. saving strings, ints, simple stuff
then whats the point of the playerprefs part?
consistent location? 1 method to save to file
you can still use json into a string playerprefs is what I meant
json is just a string formatting
I mean, idk how much it'll end up taking storage wise over time but in my write-up for the problem and solution this is a local save so it'd only be one computer
idk what im trying to say
just serialization i guess?
just saving to a file that is a json formatted text 🙂
ahh ok. lol. i used "data.spawnsave"
having my own filename extension was pretty cool to me lol
ya, basically i just wrote out structs for everything..
so even doing JsonUtility and then saving that into PlayerPref.SetString is serializing
its just limited to string size in PlayerPrefs
json'd those into a notepad file disguised as some cool proprietary save type
BUT, wasn't very secure
switch (Order)
{
case RotationOrder.XYZ:
transform.rotation *= Quaternion.AngleAxis(LookRotation.x * Time.deltaTime, Vector3.right) *
Quaternion.AngleAxis(LookRotation.y * Time.deltaTime, Vector3.up) *
Quaternion.AngleAxis(LookRotation.z * Time.deltaTime, Vector3.forward);
break;
case RotationOrder.XZY:
transform.rotation *= Quaternion.AngleAxis(LookRotation.x * Time.deltaTime, Vector3.right) *
Quaternion.AngleAxis(LookRotation.z * Time.deltaTime, Vector3.forward) *
Quaternion.AngleAxis(LookRotation.y * Time.deltaTime, Vector3.up);
case RotationOrder.YXZ:
case RotationOrder.YZX:
case RotationOrder.ZXY:
case RotationOrder.ZYX:
break;
}```
So I'm just testing rotation orderings with AngleAxis and it seems like the ordering is showing zero impact to the rotations or am I missing out on something here
and wasn't really moddable either.. as it was just settings and.. level number
i guess u could skip to the end like that.. but thats kinda lame
What's the typical FPS rotational order?
true
unless u count those leaning mechanics
maybe character does a fancy barrel roll xD
quaternions have ordering which is why I'm doing this but I'm not seeing the differences on these specific cases
umm.. i never done it like this so i cant say.. usually i rotate the player (capsule shape) on its Y axis.. and then the camera is parented beneath.. and it would rotate locally on its X axis..
Also another thing I was meant to ask of less importance, how do you make it so that the text on buttons is less blurry (idk if that's a me issue but it always seems to be more jagged in the game)
ya, i get the multiplication part..
what is the purpose for this script
but its crazy to see in a switch like that.. idk man lol i just aint never seen it hehe
ohh dang I wish I knew rotations that well enough
at y 90 my camera was flicking around
with euler
I guess fps games don't let you do 90 anyway but still
i normally also dont rotate camera for fps(only X), just the char's Y
makes sense. Not exactly doing this for a fps but the targeting still applies similarly
need the x-tilting and stuff
ahh, not sure, how does LookAt() do it?
magic
are you using TextMeshPro?
Ye at the moment
public void LookAt(Transform target, Vector3 worldUp = Vector3.up); ```
Yeah, I'm not sure but since it's not specific to an axis I guess it'll use a combination of axis by refering the world up direction?
idk this is #💻┃unity-talk question, maybe make sure Game View isn't zoomed in above 1X?
Yeee sorry mb 😅 Ty tho
LookAt would just be transform.rotation = Quaternion.LookRotation(target.position - transform.position, worldUp);
or something similar
anyone know a good tutorial or smth on how to make a good floating enemy boss ai
even though quaternion multiplication is not commutative, it seems like multiplying by each axis doesn't seem to have affect on the ordering. Atleast through the AngleAxis method here.
now watch me be wrong and it'll bite me in the butt later on
but then there's these operations which do have an impact on the ordering:
Quaternion rotatedDirection = Quaternion.LookRotation(direction) * rotation;```
Rotating by a orientation made with LookRotation is so bizarre lol
I doubt your testing method is correct if you're seeing that
so when the guy slashes forwards with his sword in hand i want the shield box to cause it to not hit the capsule but when i cause it to play the animation it doesnt get effected is there a way i can fix that
you need to code that "rebound" action in
depends how you're currently detecting collision from sword/hand
Are you talking about animation, collisions or game logic?
technically animation and collision i want collision to be the reason it cant hit it
That's gonna be difficult to implement.
You need IK
but if i cant i just thought about it and i could just do a trigger that un plays the attack animation
nvm i think im just doing to much tbf
A simpler way would be to make the sword collider ignore collisions with the character at certain point(when the character equips/uses a shield or on collision with the shield)
My testing method is starting out with an identity quaternion and then rotating by each axis in an order for all combination of xyz. So far by just observing the rotation through update, it's been consistent to every combination I've given it.
i may try that thank you
ok, so if I were to pick a ordering and add angles one by one it seems to be consistent to all rotational orderings, but if I were to update two angles at once then there seems to be some ordering relevance.
Not sure what you mean by one by one
start at an identity and add angles to the x, then the y and let it rotate
it'll always end up in the same rotation no matter the ordering
That's what my code is doing, no? And it's different depending on the order
right, was this based on my code up there?
Yes, but I removed the constant rotation stuff, which just confused matters
Ok, I kind of see what's going on now. So I'd assume it's YX ordering for FPS shooters because the X direction continues to say in that local direction allowing you spin the character on the y freely.
rather the tilting on the x stays consistent throughout the y rotation
doesn't seem to have problems with x at angle values of 90 either which is what I was having with eulers
https://i.imgur.com/5M1DZcm.png
when you harness the power of quaternions
I am fairly sure that your axes are reversed btw, and that when you say XYZ you're actually performing ZYX
The way I think about quaternion multiplication is A * B, A "rotates" B
where B is the original orientation and A is the rotation that's happening to it
hmm, alright. I'll be looking into it more since I'm changing every single euler method I've made, haha
thanks
right, it would be Y -> X here if I want to multiply by X then Y
such that we'd consider this as the XY rotation
transform.rotation *= Quaternion.AngleAxis(LookRotation.y * Time.deltaTime, Vector3.up) *
Quaternion.AngleAxis(LookRotation.x * Time.deltaTime, Vector3.right)```
Yes, but this "rotating by a compound axis" is a really hard thing to comprehend and I'm not sure why you're doing it
As opposed to using any other rotational method?
transform.rotation *= <- confusing
transform.rotation = easy to understand
oh, alright yeah
does anyone know why when using transform.LookAt on an empty with textmeshpro text, the text is backwards?
because what on earth is C = C * A * B
It's like... B, rotated by A, rotated by C, which is also constantly moving? It's confusing AF
I believe that's like that because I was animating it with degrees per second
otherwise I'd just set it I believe
Because that's the way the text is oriented compared to the transform
is there a way to change that?
No, don't use LookAt, use Quaternion.LookRotation with the opposite direction
wsg yall 😁 im fresh new to unity (literally just finished downloading the editor)
i want to get into game dev stuff
nice, brush up on some of your c# skills before delving too deep
c#?
yep, what you'll be coding with
aight
https://www.w3schools.com/cs/cs_intro.php
Good place to start
science is amazing
im assuming i click game dev w/ unity right?
The unity looking one, yeah. The other is c++ for unreal and other c++ game engines
do i need any of these optional things? (alrdy have unityhub
!ide
This guide will walk you through it 👇
Click the Visual Studio one
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
What's the most idiot-proof way to draw a circle (in a 2D scene) at a Transform position via code? I want to draw it at a specific frame in an Update() loop
Personally, my debugging package https://github.com/vertxxyz/Vertx.Debugging (or anyone else's) is the easiest method
lol
Otherwise you'll have to calculate a circle and use Debug.DrawLine
Which isn't hard if you know what you're doing, but it's not idiot-proof
Alternatively, you spawn an actual object in the scene, and take care to only do it in the editor
that's unexpected
Handles has draw circle I think
looks like that just draws a line segment
or maybe that's just wireframe
I already checked Handles before I asked here
it just has 3D objects
well, they never specified otherwise
I'm just debugging
It's a "3d object" in the same sense that so is anything in Unity if you rotate it
I always forget whether you can use Handles anywhere reasonable
it's not circular in the plane if it gets rotated wrong
...which it won't be, but I just figured Unity would have a circle somewhere and I was annoyed how long it was taking me to figure that out with Google
Took a few wrong turns
guys should i start a coding club at my hs? like a game dev club or smth
Go ahead?
sure why not
is it possible to use the fill method for a circular healthbar like this?
the sprite itself is square so it wouldn't work if i tried to fill it from left to right
but is there a way to actually do this using a sprite that is a circle?
need to use masks probably
what does that involve
uh, otherwise animate UVs of a quad? idk
because im on the documentation and was wondering if it would be possible to configure each slice of the drawing manually
what are handles
Handles.DrawWireArc(transform.position, new Vector3(0,0,1), Vector3.up, 360, 10);
you can do a radial fill
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Image.FillMethod.html
ah those
im listening
"Custom 3D GUI controls and drawing in the Scene view"
there's nothing else to it. just select the radial360 option instead of horizontal
yeah once i saw the drawwirearc i remembered them, used them for enemy field of view
neat
Can anyone help me understand how isBouncing is reading as true even though I only set it once and I set it to false?
!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.
Also, where do you set it to false? It doesn't look like you change it outside of the initializer, which is only the default, before being overridden by the value serialized in the inspector
It's initialized to false
it's not serialized to true
it's not serialized (not literally, anyway. I verified that the prefab's value for this is false in the inspector)
yes
Then search the scene t:Sword_Skill_Controller and find the instance that's true
do I type that in the console while the game is running?
No, you search the scene in the hierarchy window
ok let me check
yeah, it instantiates a sword with the value being "true"!
why tho
that is so unexpected
what's the point of initial values then
I guess I'll try setting it to false in Awake()
Presumably it's being set or animated, or you're doing something else I can't tell
I swear I only made this here
The point of initial values is to give it an initial value. It of course isn't just flipping it without some code telling it to, somewhere.
that variable doesn't exist on another object and it isn't used in other scripts
Do a reference search in code
I checked to make sure
Someone has to be setting it to true
setting it in Awake() fixes the problem
...meaning it's not being forced true after I set it in Awake
something is happening when it is instantiated
the gameObject it makes
this controller thing
must be
or rather
if it was, it would have been true after setting it false in Awake(), right?
setting it false in Awake() "solved" the problem
Can you select the prefab from the reference that's spawning it without opening it?
but it isn't clear whey there was ever a problem
Depends on who sets it when
let me see
oh...that's weird
so...I have a "Skill Manager" for these swords
and the value is true
but the sword prefab's value is (correctly) false
so it was all about serialization after all
it was exposed in two places and I didn't realize
thank you @north kiln
and @charred spoke
@frosty hound
Do you have two prefabs, or are referencing an instance somewhere else or something? I don't really understand why there would be multiple
His prefab is under another prefab and thus isBouncing being true counts as an override
And now you have learned an important lesson. Since the sword skill class is responsible for keeping track of and reacting to bounces that variable should be private to that class.
So this variable belongs to a script called "Sword_Skill_Controller" and there is an empty in the scene that has it. The controller's job is ultimately to decide what skills the Sword object has and to handle their logic.
When the game runs, it give the sword prefab a skill. The value of isBouncing for the prefab in the Project view is different from the value when I open it up and look at it.
yeah. Maybe it's a bug that the tutorial guy catches later
Or I copied it wrong 👀
actually, turning it off in the script was the overide on the sword...but not the manager for some reason
I take it back, I still don't see the "override" button on the sword object so that object is correctly updating with my intentions
This is an essential insight, thank you
Look into getter and setters for properties
Why cant I modify structs in a foreach loop?
Because structs are value types
because the local variable created as part of the foreach loop is a copy of the object stored in the array
how can i make it so everytime i press a button the activation state changes?
i want so everytime i press E it disables/enables an audiosource
like a toggle?
ye
public bool toggle;
void Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
toggle = !toggle;
audio.enabled = toggle;
}
}```
how about
audio.enabled = !audio.enabled
Oh this would be way more concise 💯
you should really start by learning the basics before trying to make games. there are beginner C# courses pinned in this channel
(besides obvious resons) why u say that
! flips the boolean to its opposite value, so if it's true it becomes false or if it's false it becomes true
makes sense, thanks again!!
! means not. So if a bool is true, then !bool is false. The main idea is that you would use it to flip the true/false value of the component.
for literally the obvious reasons. would you rather blunder along blindly and be much much more likely to fail? or would you rather have at least some inkling of what you are doing
yeah that is the most logical course
but for this game im really going for the "do i want to expert on this?" so kind of not so worried about failing
its kind of a 'test'
are we passing your test? 😄
the community is being the best part so far <333
everyone is so polite to each other
(and REALLY patient)
also just to make sure i got it right, object.IsActive = !object.IsActive
mb
that'd work right?
no
well yes. but also IsActive isn't a thing
SetActive is a method so you cannot assign to it. you can pass it a bool though and you can use the ! operator said the bool if you want to use the opposite of its value
damm, smart
literally just basic concepts
okey :D
ok so, this is supossed to tp the monster randomly when he gets in the triger, not working for some reason
start by making sure that OnTriggerEnter is actually being called
https://unity.huh.how/physics-messages
This function is supposed to contain logic for a sword stuck in something, whether that be an enemy or anything else. The "if()" statement in the middle prevents the sword from staying stuck in an enemy when there are more enemies left to hit.
private void StuckInto(Collider2D collision)
{
canRotate = false;
cCollider.enabled = false;
rb.isKinematic = true;
rb.constraints = RigidbodyConstraints2D.FreezeAll;
if (isBouncing && enemyTargets.Count > 0) // allows sword to stop spinning and stick in ground if close to a target during bounce skill
return;
//"If not isBouncing or we have no more enemies to bounce to"
anim.SetBool("SwordSpin", false);
transform.parent = collision.transform;
}
I would rather not interrupt the logic this way. Instead, I would rather remove this if() statement and put the last two lines in the inverse "if()" statement. I figured that DeMoran's Law would help me construct this, but I am having difficulty interpreting it.
(A ∩ B)' = A' ∪ B'
the inverse of ("isBouncing" and "more than 0 targets") is "not isBouncing" or "0 or fewer targets"
🤔
actually, maybe I do get it. Let me try again
that worked 🙂
I don't know why that didn't make sense to me a minute ago. It sounds perfectly logical now.
...and the code is more focused 😉
I am a LOGICAL MELON FARMER!
ok, u can call me stupid (again) but the reason it wasnt working was cus the monster didnt have a colisor
i made a long time ago ok, didnt remember i hadnt put a colidor in it
I didn't even touch anything and somehow gave myself more errors. There's more in the yellow box regions. Can someone please help me?
Also
None of my things are showing up in inspector
I just......how?
You have two files named ClickerScript in the project
The error is pretty self explanatory
Is there an easy way to figure out where the second one is? Cause I've only made one script for this whole thing
Just search for the name in the project tab
You have either duplicated it or made a new script with that name
It duplicated
Found it
Thank you!
Still have errors, but a whole lot less lol
Any chance you could help me with this too please?
I, unfortunately, copied this from a youtube video and the "this" wasn't touched on and now I'm just lost
Also, I'm still not getting any of the things in inspector....
== is for equality check = is for assigment
Thank you!!!
Lmao this is the same kind of stuff that always screws me up with papyrus too 😂
I suggest you do a beginner c# course before continuing otherwise you are not going to have a fun time making a game
Funny enough, I'm actually having a ton of fun doing this. I learn better by screwing up and talking to people than I do with courses/videos 😅
Confusing = and == isnt exactly screwing up. Its lack of basic knowledge that simple hinders progress
It's like the boy who cried wolf. If you keep on pestering people with these basic questions that are easily solvable if you put a little bit of effort, you'll stop getting responses eventually. It's not the first time something like this happened on this server.😅
I'm about to learn coding using the unity official tutorial on the website, any parts I need to really pay attention to? And should I memorise the code lines or what each word means?
its not about memorization but how to problem solve
what is a scene
what is a gameobject
what is a monobehavior
what is a component
what is the difference between a plain c# script and a script inheriting from monobehavior
you also do need to know basics of c#, which is its own thing external to unity. you dont need to exactly sit there trying to memorize syntax or the name of methods. With practice, you'll remember it anyways but you'll always have google and should be looking things up when you cant remember.
additionally,
what is a constructor -> why can't you use a constructor when inheriting monobehavior
what is the alternative to using a constructor if we cannot use it
what is serialization
why do we set values from the editor to our object scripts (components) and what are the benefits
Hi
how can i normalize speed of charactercontroller when going up and down ramps
they seem faster than walking on flat surfaces
my movement is controlled by root motion
I have a question
So when i change a feature in visual studio and come back to the scene, there is a load time where it checks the backend, then i need to press the play button to look at another load time until i can test the feature to see its not working.
Im just curious, is there an easier way to do the process above? Like some debug mode or something
You can save time if you enable fast enter playmode, but you need to ensure you reset your static variables manually https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html
Read all the documentation (especially the subpages) if you plan on using it
Will do. thanks!
Wait one more question
Do most devs use this feature? Is this a conventional way of doing this?
I cannot speak to most devs. I use it on every project, and advocate for its usage. But if you're using assets or have written code that hasn't catered for it you can experience bugs that will be confusing based on the incorrect state of static variables
it is significantly faster (almost instantaneous on small projects) to enter playmode, which is a massive productivity boost
Yes i definitely need that right now
Also, just general advice for debugging: use the debugger to do debugging. By adding breakpoints and tracepoints instead of logs you can avoid recompiling just to check logic or state
Oh jeez, i need to read up on all this, thanks anyway!
There's resources related to the debugger pinned to this channel 👍
Is this code begginers or C# beginners?
my guess is you are taking horizontal and vertical input in at the same time and they are adding together. Can you post the code you have for getting directional input?
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
if (direction.magnitude >= 0.06f) {
float targetangle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cameraTransform.eulerAngles.y;
other stuff here
}
and then i just lerp the player angle to target angle
and play animation
the rest collision n stuff are handled by charactercontroller
ok so here is the neat thing happening (I think)
Because you normalize the direction vector, the character travels at the same speed (prior to applying speed, I mean) regardless of whether they are on flat ground or a steep incline.
...and that probably looks weirdly fast to you
in fact, I just wrote some code to make my character climb steep slopes when they couldn't before
they are moving at the same speed up the slope as on flat ground
it looks a little fast, but it keeps the action moving and I don't mind it
Is the speed "increase" more serious than just this? Maybe something else is going on
my character doesnt jump
I mispoke
i checked velocity
flat = 5~6m/s
incline = 6~7m/s (depending on angle)
so yea it is faster
show more of the code, like where you do the actual movement
void Update() {
movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
if (direction.magnitude >= 0.06f) {
AnimatorStateInfo currentState = animator.GetCurrentAnimatorStateInfo(0);
float targetangle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cameraTransform.eulerAngles.y;
if ((animator.IsInTransition(0) && animator.GetNextAnimatorStateInfo(0).IsName("run anim name")) || (!animator.IsInTransition(0) && currentState.IsName("run anim name"))) {
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetangle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
}
mAnimator.SetBool("isRunning", true);
} else {
mAnimator.SetBool("isRunning", false);
}
}```
and the running bool just makes the animations play by the animator controller
and then anims' root motion moves the character
hm what components are on your player? I think you have no control over it then because you are using animation movement
i assume you have a rigidbody which is keeping your player from going into walls and such
yea the CC will handle depenetrations, but still i dont think you have any control over the speed here because its animation movement. The animation is trying to move just along a flat surface i assume, but the CC is also depenetrating and moving it up the slope at the same time
Is this code begginers or C# beginners?
Unity beginner coding
What's the actual concern?
Answer pls
If it's c# with Unity and relative to beginner concepts, this channel is fine.
If it's unrelated to Unity, it's not meant for this server.
Exactly
There's also a !csharp server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
That's not what I asked
If this is your question, then no, other scripting languages are not really supported anymore
What's supported other than C#
Relative to Unity, code would be referring to C# unless you're writing shaders ( #archived-shaders )
nothing other than c++ but that is only for native plugins not regular gameplay scripting
Nothing
So we can assume C# code beginners chat
Code refers to c#. Understand what you're asking please.
Unity coding beginner
why are you so hung up on this mate. this is the beginner code channel. it is for beginner coding concepts in unity. that means c# related questions that are relevant to unity.
I asked about unity programming choices
I got answer C# server
c#
Yes please understand what u are answering
That's all I needed, bye
Thx for the answer
We're assuming you're attempting to ask unrelated questions to Unity by blurring the border between c# and coding - happens every once in a while where someone attempts to reason why asking non unity related questions should be allowed.
How can I set default parameter values for inherited parameters? 🤔
Show an example of what you mean
I'm putting default values in all my scripts because I don't trust [SerializeField] anymore
ok, one sec
Ah with inherited parameters you mean inherited variables/members
yeah
I think you can only do that with a property, not with a field
I never asked about other programming language that is not related to unity did I?
in my Entity class, I have
[Header("Knockback Info")]
[SerializeField] protected Vector2 knockbackDirection;
[SerializeField] protected float knockbackDuration;
and in my Player class (which inherits from Entity I...don't. I don't have these parameters. They are serialized, but I want...oh wait
You asked if it's a c# or coding channel. The latter being an umbrella for the first.
Where Unity uses the first.
bye
You can also do this if you use properties cs public class Parent { public virtual float MyFloat { get; set; } = 123; } public class Child : Parent { public override float MyFloat { get; set; } = 0; }
But not sure if that's what you want
Yeah Awake works too
will these values be exposed in the Inspector?
[field: SerializeField] should work
It serializes the 'backing field' of the property
Which is what holds the actual data
!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.
Sup, i have a question, i need to make RaycastHit2D ignore 2 layers, but idk how, i'm currently using this, is there any way to do that?
int layerToIgnore = LayerMask.NameToLayer("NotGround");
int layerToIgnore2 = LayerMask.NameToLayer("Player");
int layerMask = ~(1 << layerToIgnore);
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, checkDistance, layerMask);
if (hit.collider != null) grounded = true;
else grounded = false;
// Debug.DrawRay(transform.position, Vector2.down * checkDistance, grounded ? Color.green : Color.red);
// Debug.Log(Physics2D.Raycast(transform.position, Vector2.down, checkDistance, layerMask).collider.gameObject.name);
layerToIgnore |= LayerMask.GetMask("Player");
I think that may work
oh wait what's nameToLayer again
Gets layermask with this name
NameToLayer returns the layer index, not a mask
you can just use LayerMask.GetMask, pass in the two layers you want to ignore then invert that. or create a LayerMask variable, serialize it, and assign it in the inspector instead of all this
okay...
thank you so much
Im having an issue when reloading a scene (so I can start a new game)
from the console, it looks like I am calling a method inside myClass (inside another gameobject than my player), but since it destroyed (because I reloaded the scene) there is an error
can this be the issue ?
// inside PlayerController class
public static event Action PlayerStartPlaying;
//somewhere inside
PlayerStartPlaying();
// inside myClass
private void Awake()
{
PlayerController.PlayerStartPlaying += StartGeneration;
}```
is there a way to "clear" the PlayerStartPlaying callback (is this the good word for this?)
you can assign null to it (from within the class that owns it)
okay
how do I assign null ?
it tells me that I can only do -= or +=
maybe I can just do
//On Disable
PlayerController.PlayerStartPlaying -= StartGeneration;
idk if this is the correct use
you can only assign null to it within the type that owns it. the whole point of decorating it with the event modifier is so that other objects cannot invoke it or modify it except for subscribing and unsubscribing
but if your intention is to just unsubscribe the one method from it, then yes -= is how you do it
Hi, i have a weird problem with my rotation. My Code is very simple, i want a gameobject to look away from another gameobject
Vector3 direction = new Vector3(unit.transform.position.x, 0, unit.transform.position.z) - new Vector3(MainPoint.transform.position.x, 0, MainPoint.transform.position.z);
Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
unit.transform.rotation = rotation;
As you can see in the picture, the rotation is nearly right, but not exactly. What do i miss here? Thanks for any help
Oh the red line is a debug ray, which shows the correct vector3
does some1 know how u play a partical after a given amount of time
trough script i guess lol
set delay
for the debug ray, what values are you using to draw that? Also what object is the unit, what is the MainPoint? the code looks fine to me
the same which are used for the direction vector. I tried my code in a clean project on 2 cubes and it works fine, so i guess the code is correct. Now i have to find out what could change the rotation slightly. Maybe the Pathfinding somehow... but thanks for reply have to debug now 🫠
I have a question.
Is there a best way to access object's script, or GetComponent<>() is best i get?
Could try disabling scripts until it stops rotating. I think the only built in causes for rotation could be rigidbody, navmesh agents, or a parent transform rotating.
That and TryGetComponent. You dont really have any alternatives if the only thing you have access to initially is the gameObject
Well, as i thought. Thank you for the answer.
Could do with a little help debuggin please. in my current scene the main scene i have the player prefab in the scene all my animations work fine. but as soon as i delete him and load him with my Instantiate script one of my animation.. well my only Any state animation wont play and the player freezes. This only happens if i Instantiate him. I have 3 scripts attached. my state script. my player controller script and my DDOL script. https://gdl.space/cetupiziwu.cs
line 126 debug does get called if (Input.GetMouseButtonDown(1))
{
Debug.Log("Attcking");
playerState.ChangeState(PlayerState.State.Attacking);
}
but then freezes. in the animator the all the animations stop
again this only stops working when the attack is trying to play when my player objected is being Instantiated
im almost at the verge of braindead, i need to draft something out lol
if(A && B && C){
bool = true;
}else{
bool = false;
}
if(B && C){
bool = true;
}else{
bool = false;
}```
so A is unnecessary?
correct
thx
guys what is going on here. I have variable moveSpeed with which i want to adjust speed of capsule that i want to move around. But regardless of its value even if i lower it by 1000, capsule moves the same speed and very fast for my liking. how should i fix this
is the var public and is it different on the game object. might be trying to over ride it in the script but game object is changing it
no wories been there done that lol
completely forgot that i set it in game object

i was pissed at chat gpt i tell it to fix code something is not working, i tried 5 different versions and all the same. now for obvious reason

is there an optimization or profiler channel?
any ideas i could try?
return;
after Destroy(gameObject);
in PlayerController
would be a good place to start
thanks
also your singleton pattern should be in Awake not Start
thanks ill change that. was thinking about ditching the singleton any
has anyone tried his state machine https://www.youtube.com/watch?v=RQd44qSaqww&t=14s
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
In this Unity tutorial, We'll use, from the ground up, the State Machine programming pattern to setup some simple logic for o...