#💻┃code-beginner
1 messages · Page 706 of 1
what game should i make then
Start simple 2d platformer then go bigger on your next project
idk how to make a 2d game
Look on google youtube and such pleanty of tutorials for you to start.
Pong
No clue at all how to do that
Perhaps game development is not for you then ?
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Nah just Tryna learn
I am also a beginner right now i am watching Unity Learn Junior Programmer pathway
If you have finished the junior pathway you should have an idea of how to make pong. If not, sit down and break down the game into small problems then start tackling them one at a time
I am still watching so idk pong right now
I was referring to the other guy who claims to have completed it
Why are you learning game dev then?
I don't understand
don't you want to learn to make games?
@lofty mirage have you figured coroutines out?
I mean I'm used to just declaring them as
private Coroutine coroutine;
starting them with
StartCoroutine(coroutineFunc());
and having coroutineFunc() defined as
private IEnumerator coroutineFunc() {}
It was more to understand if there were some other ways of doing it I guess
but my "baseline" works
Did you want to ask a question or were you just checking up on me?
If the latter, that's very nice! 🙂
Now i feel bad for wanting to ask smth <-
haahhahaa
Well basically if you use yield return you have to put the statements in a IEnumerator function
you can't start an IEnumerator function without StartCoroutine(IEnumFunc()); in my knowledge
the main important things I think
Was that your bug?
(public void StartCoroutine(int waitTime) { if (isCoroutine == true) { coroutine = WaitAndDisable(2); StartCoroutine(coroutine); } })
Wrote it like this and i think this fixxed this?
(technically just the function signature)
( private IEnumerator WaitAndDisable(int waitTime) { yield return new WaitForSeconds(waitTime); })
So what did you do different before?
Although I would rather write:
coroutine = StartCoroutine(WaitAndDisable(2));
Also, I'm not sure what you're trying to achieve with this public void StartCoroutine() function
Isn't your end goal just to WaitAndDisable for 2 seconds?
nvm dind't fix it 😄
In which case you would just write StartCoroutine(WaitAndDisable(2)) at the place where you want to WaitAndDisable 2 seconds
I'm still extremly new to coding so i'm just throwing paint at the wal and hope a masterpiece somehow comes int oexcistence
technically i wanted to edit waitTime in the editor, to test some stuff (removed the 2, was from a test earlier) but still I think I'm approaching my task the wrong way since it's not working like at all
Yeah okay haha
My issue is, that I'm having a button taht i want to click to continue with an animation but during the animation (which is the waitTime) I want to disable some ui element. This way I though there's a clean transition from color to black and then again from black to color
disable, you mean so that it's not "clickable", or cannot be seen at all (and not clickable)
the later
oh okay
do you know where in code you want to trigger the disable coroutine?
Maybe your UI button OnClick() triggers a function?
doesn't the coroutine disable itself after waitTime?
yeah it triggers the StartCoroutine fucntion
oh okay
well first of all I wouldn't call the function StartCoroutine()
because that is an in-built function name
so that may cause some problems
Maybe you can try:
OnClick() -> DisableButton()
using UnityEngine.UI;
private const WAIT_TIME = 2f;
[SerializeField] private Button myButton; // you have to drag in the inspector
private void DisableButton() {
StartCoroutine(DisableForTime(WAIT_TIME));
}
private IEnumerator DisableForTime(float waitTime) {
myButton.enabled = false;
yield return new
WaitForSeconds(waitTime);
myButton.enabled = true;
}
I just coded this on the fly on Discord for you
I think that should do it
don't forget using UnityEngine.UI
since I believe that you have a UnityEngine.UI Button element (?)
or is it just a gameObject?
if the latter, you can replace myButtonenabled by gameObject.enabled
so what I want to do isn't disable something temporary, but forever basically (if the player doesn't restart the level).
My intention is to waitTime, till the animation transition finished, then I'm going through two foreach loops: One to disable an array of Objects that shouldn't be active anymore after the anmation ended and one that enables objects that hsould then be visible
so I don't think disable button is the correct approach
So you want to deactivate only after 2 seconds?
yes
Maybe you can try:
OnClick() -> DisableButton()
using UnityEngine.UI;
private const WAIT_TIME = 2f;
[SerializeField] private Button myButton; // you have to drag in the inspector
private void DisableButton() {
StartCoroutine(DisableForTime(WAIT_TIME));
}
private IEnumerator DisableForTime(float waitTime) {
yield return new
WaitForSeconds(waitTime);
myButton.enabled = false;
}
My button press:
- Triggers an Animation
- After x seconds disables ui
so like this? (I updated DisableForTime)
you can replace the myButton.enabled by all the things you want to disable
here I put myButton data type because I don't know better your data structures
SetActive() can work too I think
to hide the whole button SetActive() is better
Otherwise changing the button interactable state is the other approach
Basically pressing the Button that's a child of Task_Front, disables Intro Anim and Background Black and trigger the Fade To Black Animation
True, .enabled is more for components like spriteRenderers I guess
yea thats right. It would "disable" the button but not change its visual state
i dont want to disable the button, but like everything .-.
then do things to your parent container?
canvas group can be used to change the alpha of the whole object and its children
Then like:
OnClick() -> DisableButton()
using UnityEngine.UI;
private const WAIT_TIME = 2f;
[SerializeField] private GameObject introAnim; // you have to drag in the inspector
[SerializeField] private GameObject BackgroundBlack; // you have to drag in the inspector
private void DisableButton() {
StartCoroutine(DisableForTime(WAIT_TIME));
}
private IEnumerator DisableForTime(float waitTime) {
yield return new
WaitForSeconds(waitTime);
introAnim.SetActive(false);
backgroundBlack.SetActive(false);
}
What do you think of this @fickle stump
Hi, i have a question , did a prefabs that need another instance like player component for it status or the gamemanager, it need to auto get it as yoou can’t drag and drop it in inspector

You should set those fields at runtime using some other component
e.g. spawn player prefab, assign game manager reference
There are many ways to do it, the beginner way would be to use a find in the player component.
The best way is to use a script to create that prefabs then assign the ref it need ?
Yea, if you have something that spawns the player, it can initialize the player/set these important references right after.
oh okay lol
It happens don’t mind haha
Well it depends if you spawn the prefab during the gameplay or not
if it should be there since the start you can just drag and drog using a SerializeField
but if it's initialized during the game, then yes, you need to declare, initialize, and store the prefab in some variable in your script
Nop, i try to make a dynamic spawn as it play on multiple scene but all my core systems is init only one time between scence change and at start but some is init later for optimisation 
okay then scripted all the way then
Is it a bad idea if it set some variable itself ?
wdym some variable itself?
You do use gameObject.function no?
function being whatever like .enabled etc.
Would it be possible to make the start of an action depend on the keyframe of the animation? I wanna spawn a bullet at a specific time and was wondering, if I could use the keyframe of the animation to determine, when the bullet is supposed to appear
Yes. Look up animation events.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What is your "coresystem"?
Like a GameManager?
An instance that registe all other manager
Prevent multiple static instances
What makes your PlayerInputHandler difficult to reference?
It an exemple but here an exemple
(How we share code with past mod)
if its a singleton then the player itself could retrieve the reference or just use the static field
otherwise as I said before, the class that performs the Instantiate() can also init state
using System;
using UnityEngine;
public class NPCDialogueTrigger : MonoBehaviour
{
#region Script Parameters
[Header("Visual Cue")]
[SerializeField] private GameObject visualCue;
[Header("Ink JSON")]
[SerializeField] private TextAsset inkJson;
#endregion
#region Fields
private DialogueManager _dialogueManager;
#endregion
#region Unity Methods
private void Awake()
{
visualCue.SetActive(false);
}
#endregion
#region Methods
public void SetInkJson(TextAsset newInkJson)
{
inkJson = newInkJson;
}
public void SetVisualCue(bool active)
{
if (visualCue != null)
visualCue.SetActive(active);
}
// Trigger dialogue with this npc
public void Interact()
{
if (inkJson == null)
{
Debug.LogWarning("No Ink JSON assigned to this dialogue trigger");
return;
}
if (_dialogueManager != null)
{
_dialogueManager.EnterDialogueMode(inkJson);
}
else
{
// Auto Set Dialogue Manager if not set before
if (CoreGame.Instance)
{
_dialogueManager = CoreGame.Instance.GetService<DialogueManager>();
}
}
}
#endregion
#region Implementation
#endregion
}
ops
you missed the 3 ticks at the start
This is long enough to be shared via a paste site.!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
backtick
' ` '
this character
3 times
Oh thx
Thanks o7
but sorry, I'm not too familiar with managing multiple scenes variables / objects at the moment
Oh no problem
I dont think there is more to say

Oh btw
I noticed you use the region thing
what is the point of it?
Just to click on region to "close" the visual for the code region in the IDE?
Can someone give a direction where to look to make seamless 2d world like in Starbound, where player reach edge of the world and could just move forward without changing his position in code?
It's likely that the world is broken into chunks that are placed dynamically, and when the player reaches the edge of the map, a chunk from the other edge is spawned.
And the player position is likely reset somewhere. Possibly on these edges.
Thank you
Yeah that seems to be the most likely
public static T CloneInstance<T>(this T obj) where T : class
{
var json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<T>(json);
}
anyone has a better way of cloning a class instance beside creating a constructor with all the fields?
Someone got an idea how I can prevent clicking on UI, while a certain UI is active?
basically while my book is active, I don't want the user to be able to click on the buttons at the top left and the bottom right
an image covering everything that blocks stuff you don't want to be clickable.
disable the canvas raycaster is a quick solution
canvas groups I think have a sub property for that too?
yep
That's the quick and dirty solution
and i'm so gonna take that xD
Making it black and giving it 50% - 75% alpha helps make it obvious too
For future reference - UI questions go in #📲┃ui-ux
What do u guys usually use OnGUI() and GUI skin for?
I find the Canvas system is way more efficient when it comes to many UI tasks
nothing
no one uses ongui for game ui anymore
actually i lie
i use it for a little debug console built into my package because i didnt wanna mess with prefabs in a package
if its not real game UI its okay.
UGUI or ui toolkit are the 2 choices
well ui toolkit only needs a component to draw the ui document
i get why its great in fully fledged projects but i have zero interest in using ui toolkit rn because i (afaik) can't do it all in c#
You can do UITK editor stuff all in C#
I do not know if that's the case for game UI with it
either way, doing it all in C# or with USS/ UXML(?) .. it's an awful lot of code
you can build ui with code for both but its gonna be a pain, more so I think for ui toolkit
eh maybe im a freak but i don't mind it too much, maybe i haven't dabbled into the super crazy stuff yet
It's been prob 2yrs since I was messing with UITK editor stuff, I remember struggling to get the right element.. had to keep going into the debugui builder thing and going down all the various trees etc
yeah as soon as you get more complicated UI you dont want to do it in c#
UGUI is perfectly easy to learn and use
UITK isnt there yet imo
I just hate how component pilled it is
component pilled?
that's unity though - everything is components
Like a majority of it is heavily reliant on monobehaviours utilizing transform positions
RectTransforms!
ui toolkit probably did the right thing and stopped using a gameobject for each element
as carwash said they rely on rectransforms, also yeah cause monobehaviour is the way to script here and I dont get why you think its bad 😄
If you want to stray away from Unity's own collection of monobehaviours i think there's not too much your actually reliant on (couple colliders and renderers, maybe some physics stuff). with the UGUI stuff though it's heavily tailored towards that setup
i'd prefer to control a lot of that stuff in code directly
no not really, you can recreate basically everything from a button to text to scrollviews
you can even look at the code of how unity did it, its included with the UGUI package
It's a tough ask when you have to deal with topics like batching and font renderering, unless i have been missing stuff
then stop reinventing the wheel 😄
i mean sure but that wasn't my point 😛
immediate mode gui is convenient to code but not really ideal for a game perf wise
so ideally you migrate to a supported ui solution
Unity would love you to use ui toolkit but i've yet to change
Doesn't have world space UI yet, not possible for anything VR or AR
yea not sure how thats not possible yet, even via rendering to some render texture
After going through the torture of using ECS when they announced it first useable and managed to make their own guide video obsolete after a mere 2 months and cancelling multiple solutions they praised in high tones to be the next big replacement, I dont touch new things in unity with a 10 foot pole until it has some adaption
ECS has always puzzled me, they go to such amazing efforts to make c# be like a native lang and engine features seem to need whole new versions to even be usable with it
oh no the current version of ecs is fine and it makes sense they have to rewrite a bunch of engine features on the new coding style
but the way the handled the introduction was abysmal
I've tried it but not had a big need to use it just yet. hopefully it improves more to be easily usable with most features
We currently still use the gameobject approach but our pathfinding runs on ecs in the background and then syncs the position to the enemies
why not use burst jobs, seems like you almost are already
i mean its uses bursted jobs and data is handled on the ECS approach, its an entirely decoupled system from our normal code
sounds like you have entities there for no useful reason but its working
unless they keep state re used all the time for pathfinding
yeah its not pathfinding that just runs once and we are done, its recalculating everytime the player walks more than 0.5 units and has local avoidance
Yes but I cant
ok i think i'm loosing it:
Shouldn't this literally toggle the object on mouse 0 click
No need to drag this out again. If you want to learn start with the link you've been provided, you can find comprehensive Pathways courses there.
You can just do:
foreach (GameObject toggleObject in toggleObjects) { toggleObject.SetActive(!toggleObject.activeInHierarchy); }
As for why it's not working - add debug logs to find out if:
- the method is being called
- the foreach is running
what does this last part do?
!toggleObject.activeInHierarchy if it's not active in hierarchy I set it Active, but does it also disable it?
toggleObject.activeInHierarchy is a bool, ! "flips"/"reverses" the bool
if on, off
if off, on
Well here you have a list/array of objects
if it's active, it's made unactive (and conversely)
imagine a flicker
but each flicker "tick" is a function call
either that or a parent is inactive and it's trying to toggle the child
oh yea, danger of not using activeSelf
yeah i found the isuse i think but this just confuses me more lol. For some weird reason I can only toggle it from the top and not from the sides of the object oô
those weird mouse events are kinda shit
its better to use a collider + event system + IPointer events
when doing aiming from a top-down camera, do i make a separate script or do i connect it to the camera itself or the player its following
Whats funny is, if i zoom in the camera a bit, then it's no problem clicking on that cube
yea that system is funny and I dont fully know its rules
Aparently it's because of cinemachines near clip plane beeing too low
those monobehaviour mouse functions have nothing to do with cine machine
then i'm confused why it suddenly works after i adjusted the nearclip plane
lol
oh
i know why 🤦
I've put invisible triggers between the camera and the object to check if an object leaves my grid
and the ray from the camera constantly hit those triggers therefor i was unable to click on the objects, since they were behind the invisible trigger. Using the near clip plane the camera ignored the triggers infront and went straight onto the objects
If you use the event system way you can specify the layers it uses
(requires a physics raycaster as well to work)
Ok kind of a weird question but are you able to access a prefab via script and manipulate it during runtime?
My idea would be to have two buttons which can change the material of the prefab that will be instantiated.
the problem why i can't access the to instantiate object is because I first render a third material on it
(actually I think i can just use the buttons and on button click increase the index of a count and depending on the index before instantiating, assign the material [index])
You can save the button state, and change the material on instantiate before you do anything else to it
but no, in a build editing a prefab would not be possible, the code for that is in the Editor assembly which is stripped during build
thats not true. you can load the prefab asset and manipulate it but that will only survive till that loaded copy is GD'd
I dont know if unity re uses the same instance or not but probably a bad idea
Arent the methods for that in the editor assembly?
you can load a prefab and modify the GameObject instance but its not actually modifying the stored state
Can you explain why that makes it impossible to access the object?
Ahh alright, yeah didnt think of that
sorry, misstyped "yeah" as "you" 😄
tldr dont bother and modify the prefab instance post spawn
so in my head, if i click a button and it instantly assigns the material, then I instantiate the Object with a Transparent material and after mouseclick it should go back to original
now that i think of it
ah no the way it currently works is that its loading the materials again from the prefab
so i somehow have to tell the object that will be instantiated that after placing it (mouse click), it should instead get the material that i selected earlier but not sure how i would do that
besides that way
public class SpawnedObject : MonoBehaviour {
public MeshRenderer Renderer;
}
public class Spawner : MonoBehaviour {
public SpawnedObject Prefab;
public List<Material> Materials;
public int WhichMaterialToUse = 0;
public void SetMaterialIndex(int i) {
WhichMaterialToUse = i;
}
public void Spawn() {
var spawned = Instantiate(Prefab);
var spawned.Renderer.material = Materials[WhichMaterialToUse];
}
}```
Just a simple example, then you just have to set the buttons up to use the SetMaterialIndex function
Unless I understood your problem wrong 😄
public SpawnedObject Prefab;
This is the best way to spawn prefabs, don't declare them as GameObject - declare them as a component on the root, so you get a reference to that with the spawning.
(unless using addressables where we cant 🙁 )
depends on how you load things
yea if you load the prefab then instantiate yourself it works
I dont get the benefit using InstantiateAsync() when the fuckers cant release themselves
i find i do not use it often, also often i am not using addressable references either
since i am loading a bunch of stuff via a tag somewhere then doing stuff with it in the future
you make your own addressable reference in that case
yea its just an extra get component
as long as you remember to release the gameobject later its fine
addressables are horrible to work with, if stored remotely - hate them
Ops this local thing has a remote dependency fuck you!
The effort I had to put in to ensure this didnt happen was mad
are fine no worse then assetbundles owrkflow for remote stuff
Just gonna ask for the sake of it
How much of beginner are adressables
Because this is the first time hearing that
0 much is beginner
They're not for beginners
Beginners won't be doing anything that needs them anyway
its more a feature only needed to learn about when a game gets big or for production etc
Okay then i'll try avoid to do that and work wuth the basic first
it will jsut add confusion learning it before having a good grounding in other stuff
Something like this is what i thought if aswell ye
Thats what i tried to communicate hahs
Actually a good question actually, when would you consider people not beeing beginners anymore?
Being able to build a game without learning a fundamental aspect of unity (like "how do physics work?")
Ofcourse you will have to look up details or ask questions, I do even with ~7 years of experience but that never stops
really things are large enough no one will be a expert at every part of unity
imo ur always a beginner in certain aspects.. theres things you'll do more often then others.. and some things you may never use
mixed bag
Whenever I have to look at shadercode I feel like a programming toddler again 😄
thank god for shadergraph
thats just practice, its mostly just very easy math
yeah I wanted to learn it but then unity dangled that carrot named shadergraph in my face and I never bothered 😄
yeah i sometimes use it, but for this project its all HLSL shaders since shader graph was just getting in the way
ooo scary shader code!
fixed4 frag (v2f i) : SV_Target
{
float2 uv = i.vertex.xy / _ScreenParams.xy;
fixed4 col = lerp(_Colour1, _Colour2, 1 - uv.y);
return col;
}
Its worth being able to write shader code as some things still need that
i mean i can read it if its that easy 😄, writing it on the other hand...
though be warned, urp/hdrp lit shaders will make you go mad
yeah current game is using heavily stylized shading
I don't think I'll ever try this type of stuff LMAO
so i more or less wrote the whole lighting model in a few includes so it can be called from shaders in a simlar way as the surface shaders of the past
good thing you dont have to, for small projects shader graph is perfectly fine, larger projects have dedicated graphics programmers
might as well be alchemy to me.. (atleast for now)
even know i prefer writing shaders in code now, learning with the graph i think is best
you get to see the output for each and every step which is huge when learning it
Shaders can seem difficult at first as its different vs cpu code
only thing ill have to stick my nose into is compute shaders
really i think most people just treat it like this weird black box and never look at the details
!code
alot of it is just math straight up math and thats it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I guess you can but you need to understand at some point how the end result is being produced by a shader 🤔
Ofc simplest is uv -> sample texture -> output color
now things get complex due to complex problems to solve not the shader part its self, like a full PBR lighting model is alot of stuff write and learn
where like ramp shading, cel shading or like a lambert+blinn is like 100loc of hlsl or so
Fun story: kinda sad but I'm actually a game deisgn student and i hope pray that I'll land a position in the industry as a leveldesigner and right now I also try to stick my nose into a bit of coding, just to understand everything atleast a little bit c:
(and ofc i have to submit projects for uni, so i kinda have to code)
How long have you got left?
1 1/2 years
good you got some time left, hopfully the industry will rebound by then
1 year was everything non game related, then had two semester/courses for game related stuff, then an internship at a completly different branch cuz yey internships and now two larger projects and my bachelores and I'm done
I mean, I have a stable job as QA and I don't intend on instantly leaving that position just because I graduate. Loving to work with these people and their proejct is insane
The leveldesign thing is just something I always wanted to do at some point in life. Doesn't have to be in the next 2 years or sum
so QA into design is fairly common
I think it's gonna take longer
problem with design is most studios do not need many
and here I'm getting told so many ppl need leveldesigners 
think large studios will not rebound for a long time, but i can see more like mid sized indie and AA starting up to fill a void in the near future. Hard to say, like a lot of talent was cut loose but also getting investment is very hard right now
where are you located? I see a lot of companies searching for game dev staff in berlin, except for devs itself, that role is overcrowded 😄
Germany o/
yeah well then you have the choice of berlin, munich, cologne and hamburg as the big 4 in game dev
Also if you are considering europe in general poland and netherlands are good places to be
it is crazy how much stuff changes, like way harder to get dev jobs now, vs a decade ago i accidently got a dev job
Oh well, I could have noticed that, you are actually on my server that is for the D/A/CH region 😄
Kidna something that scares the hell out of me
literally as soon as im about to graduate theres an influx of people joining hte industry
Yoo no way i thouight your face looked familiar haha
are u guys gamedev in the industry or is efveryone doing htis as their freetime fun
think large studios will not rebound for
Did this for fun for about 6 years while doing web dev, then got an offer from a game company and switched, doing it professionally since 2019 now
hi, my power went out mid coding and when i booted up the project it showed like the script references and said 'The associated script can not be loaded' and i've removed the script from the objects and tried to add it again but it's not on the list, the name of the file is the same as the class name so idk what's the problem
is there a max size for native arrays? when i make my native arrays too big they seem to break. idk if its an issue with my code or native arrays start to break with too much memory stored
Set up 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
• :question: Other/None
the script and the class-name must match.
my ide is set up
yea it does
Probably the meta file didn't save. Easiest way to fix it would be to just make a new script, copy the stuff over, and delete the old one
oh just noticed, your script is abstract as in non constructable
oh, that's right.
Oh that'd do it
why did i try to abstract it tf?? thanks
I mean pickable is a very generic name, could have been that you planned to make different ones with different behaviour, then abstract would have been totally fine as you would be able to use the inheriting classes
as you made the properties protected it seems like some kind of inheritance was planned
Does unity hierarchy not saved by a git normally? I've made a lot of mistakes and decided to regenerate project from git but now i see empty hierarchy
hierarchy is part of the scene, so did you save the scene and commit it
or did you open the correct scene again after getting the project from git again
Oh, looks like they weren't added to vc, only see scenes.meta and empty scenes folder. Thank you
ops

Sorry!
I NEED SOMEONE WHO KNOW HOW TO MAKE A GTAG FAN GAME
The Caps Lock key is a key on the left side of your keyboard, usually between the "shift" and "tab" keys
What was that for
You looked like you needed the info
I assume it was on and you couldn't figure out how to disable it
Yes. You.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ok
i'm feeling pretty stupid, how can I refine the position of my object?
When I target the tile I want to place the pointy arrow thingy at (mouse cursor at that moment is at purple circle), the way I'm rounding off the MouseToWorldPosition values make it appear I suppose rounded off to the closest number (cuz math) which places the tile to the lower left of where I actually want it to be targeted.
Now I totally suck at math, which is obviously a very good trait for any programmer to have, but how should I go about actually placing it on the tile that the mouse is hovering over, rather than rounded off to the wrong spot.
The code I'm currently using is
Vector3 screenToWorldPos = Camera.main.ScreenToWorldPoint(new Vector3(Mouse.current.position.x.value, Mouse.current.position.y.value, Mathf.Abs(Camera.main.transform.position.z)));
transform.position = new Vector3(Mathf.Floor(screenToWorldPos.x), Mathf.Floor(screenToWorldPos.y), screenToWorldPos.z);```
using Mathf.Abs for the Z position because it's currently set to -10 and I didnt want the offset to be hardcoded whenever I change the camera position above the grid
the grid by the way, is just a tiled sprite
(i wont have access to my pc for the next 3ish hours or so so I'll be responding via phone)
Is it bad practice for now to have an EnemyTypes script that looks like this...
public class EnemyType : MonoBehaviour
{
public enum Types
{
Melee,
Ranged,
Tank,
Flyer
}
}
If this is the whole script, what's the point of it being a MonoBehaviour? Why wrap the enum in a class at all?
idk, didnt know that was an issue, I was doing it to reference in my EnemyHealth script and EnemyPathfinding script to assign different health values and chase behavior without giving each enemy their own script or sharing the same stats
You can make a file that contains just an enum
Use a namespace
it doesn't need to be inside a class
Wouldn't recommend having a enum in a class as it restricts that enum to that class
as in I would have to reference that class each time I wanted to access the enum?
do you mean in vs? or like just a different file type
they are constants so it becomes part of the class
Well as in if you wished to use the enum in another class and declared it there they wouldn't reference without being their numerical values
eg EnemyType.Types.Melee
sometimes it makes sense to only keep within a specific class, sometimes it doesn't
so it would only let me access with like 0,1,2,etc instead of what the name of the class actually is
namespace Entity
{
public enum EnemyType
{
Melee,
Ranged,
Tank,
Flyer
}
}
namespace Entity
{
public class Enemy: Monobehaviour
{
[SerializeField] private EnemyType enemyType;
}
}```
I mean in the script file you are editing, there is no point to have a class in that file at all
The file can literally be just the enum
an enum is a type, it doesn't need to be in an outer scope
I'm lazy I just stick it in global usually
why an enemy class in the file with the enum? is that the go-to way to be able to reference it from another script?
being in the same file doesn't make any difference
Doesnt matter if it's in the same script, but you can have that in a different script
Monobehaviours however do require to be in different scripts and SOs
cause Unity
yea the only thing Unity cares about is not putting Two MB or SOs in the same file
As in no two monos
That's an example of how to use it, not something that should be in the same file
imo in the same file is poor organization
Nice to have a EnumUtility script, otherwise nesting them
I dont have a general Enemy class script atm, just separate ones that handle their health, pathfinding, and damage individually.
how would I assign one of the enums to different enemy Objects?
components are good but i would not go that granular myself
You would create a variable of your enum type and set it to the value you want.
so like in the EnemyHealth script, I would put
enum Types types;
then
types =
no
enum keyword is only used when defining the enum
you know i feel like this answered it pretty well https://discordapp.com/channels/489222168727519232/497874004401586176/1401962939409367162
the Types enum becomes the type
This shows both how to define an enum, and how to create a variable of the enum type
so just replace the keyword with public or private in whatever script I want it to reference
[SerializeField] private EnemyType enemyType;
is an example of how it would look in a script
correct?
Yes
that would be creating a variable of type EnemyType and assigning it the name enemyType
me when this is exactly what the script above showed
It currently does not hold a value
You would need to assign it, probably in the inspector
and when not assigned, by default the first item is used.
so by default enemyType would be Melee
Value types are never null
Right, my bad. I wanted to emphasize that declaring it is different than assigning it and chose my words poorly
can you just drag and drop the enum file in the inspector and assign it there?
You don't assign scripts to it. Its not a reference
its like saying , do I need to drag the integer class to assign public int myNumber
The enum file does nothing other than exist
You don't drag it anywhere
It allows you to create a variable of that type in other scripts
then I'm confused about this
Try it
Put a variable of that type on a script
then look in the inspector
alright
do you guys have any guides to recommend regarding learning scriptable objects, monobehaviors, game objects, their differences and discerning when to use what?
I can assign the enums, that was so difficult to comprehend for the first time
on unity !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
and !docs
ok, many thanks
Monos require game objects, scriptable objects do not.
Monos exist in the scene or as a prefab in your directory, SOs can only exist in your directory or inserted as a property into a game object
Also worth learning the differences between just plain c# data vs a scriptable object
I'm making a first person games using cinemachine. I am making it follow the player by doing this > vCam.transform.position = transform.position; this works but how can I change the Y position? when I press play it changes the Y position.
you have to create a new vector3 and move the y as needed
var targetPos = transform.position
targetPos.y = whatever;
vCam.transform.position = trargetPos``` or
`vCam.transform.position = transform.position + new Vector3(0, yOffset, 0)`
I thought Cinemachine already had such components you can play with offsets though 🤔
Cinemachine does yes
So I'm trying to make a dash, but when the player dashes upwards, the dash is stronger than a horizontal dash.
This is my entire movement script: https://pastebin.com/Ud8Y7h2f
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.
You're using the old input manager
idk how to code ;9
have you read what it says
how do I use the new input manager
have you googled it
no
Google is your best friend
did you know you can google it
Input code differs between the built-in Input Manager and the Input System, and changes are required.
Then do that before you ask for help here please
-ye
any tips I have to make a small game as my FYP in like a year (3D game) any ideas. I really want to do this so does anyone have a roadmap (Also I dont want to use chatgpt or any AI tools I want to learn as I make the game)
thks
you gotta start by !learning the basics
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks my bad ill go the to designated channel
Game development isn't easy to be honest. It groups together a lot of different skills and depending on what your expectations are, it can be quite easy (less than a month) or very difficult (five or more years).
I have a farely easy game idea in mind nothing to happening but just some fun co-op game
easy on the perfomance
nothing to high-fidelity
its sort of like a backrooms type game
with a few unconvential gimmicks
co-op?
you mean multiplayer?
yes
Iam curenntly working on a prodecurally generatred maze atm
and liek I created a simple fps character sript
following a video
i managed to learn how to use unity and create a game in like 8 weeks using chatGPT it does help to learn fail and try again until it works
had to skim though like 5-6 videos to get actuall understand it
but when I did it was so satisfying
I think you shouldn't start with a fully fletched multiplayer game.
noted
so I first go with a singleplayer
right?
I mean not gonna lie thats actually a good idea
you could tackle multiplayer
first comeplte the game on single player
and then transition to multiplayer
never thought about it like that
yes, but once again, multiplayer is REALLY REALLY hard to make
Ig it iss since making a singleplayer one is hard as it is
if you want it to be polished, then yes, it is, but when you get the hang of it, it's simple.
hey if you don't mind me asking have you created a game for phones befor?
i didn't
Thank you for your help and time
I really appreciate it
ChatGPT and ai in general is garbage for education and I highly recomend avoiding it in the future
Does anyone know why this keeps showing up, im kinda new to Unity.
Just learn yourself with google and learning resources.
so im following a tutorial about how to create a action system and these are the two functions to subscribe and unsubscribe Action delegates to a static dictionary and in the tutorial they are putting a wrapper function on it.
the problem is I'm not sure if the "wrappedReaction" in the subscribe and unsubscribe function are really equal and subs[type].Remove(wrappedReaction); will work or not
Well, have you tried it?
Tutorial really trying you save you line space that's for sure
actually it's me trying to save line space because i'm not familar with these kinds of syntax. and yea i should probably try it before asking :(
anyone?
So what's the problem? If the values are off then by what amount?
Alternatively, instead of using ScreenToWorld, you could just make yourself a large quad collider as the grid you raycast upon, or use Plane
if i wanted to create a game similar to paper mario i would have to use unity 3d version right?
ye, but secretly Unity is always 3D anyway
well, it's rounding off to the closest integer, so it makes sense
here's a shitty phone recording
start debugging the values you get back
Ok it doesnt work that tutorial made a mistake. i still don't know why tho
true
i moslty make 2d stuff tho
i really want to recreate pokemon black and white in unity tho
but i have to learn 3d stuff ;-;
3D is easier than 2D
wont be able to talk about that too much here btw 😛
i mean the values are just rounded ints but it's agressively rounding 'em down I suppose
rip 
really? oh
To me just looks like some grid alignment issues without seeing values, but what you're doing in the code doesn't seem incorrect. I can just imagine that ScreenSpaceToWorld may be giving some wrong values
Quick question, what's the best way to fire ray-cast from inside a trigger (collider) and still hit it?
For instance, you have a trigger representing Water, and you get different reaction from shooting at it and from within it.
Usually I do some overlap method when I do some like shapecast in case of spawning inside of a collider, but I don't recall having problems with raycasts for that?
Now I question if overlap would work if it doesn't intersect at all
https://docs.unity3d.com/ScriptReference/Bounds.Contains.html
That may be the solution
https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
Rigidbody has a sweep too
I should probably mention that In this case it's a 'blind' cast, so I am not casing against any particular entity, I am only testing if something gets hit by the raycast; generally a collider.
why
maybe they're doing a laser alarm that goes off when object goes in it 😛
I gave one example. Another is for instance a ladder trigger - the player presses USE on the ladder and attaches themselves to it. Once inside, they can dismount by pressing USE on the same ladder, but if I'm already inside the trigger, I will never hit it with a normal raycast.
but why do you need to raycast while your inside the ladder
How else do I detect what object is the player looking at? I'm looking for reliable methods for this exact purpose.
when you are on a ladder
do you want to know that the player is technically looking at the ladder trigger collider
Well, ideally the collider and the ladder trigger are the same thing. Of course I can offset the collider or add additional entity for no reason, but that's just bad design - it's incredibly easy to create discrepancy. Of course, the representation of the ladder is different from the ladder trigger.
when you enter the ladder you'd probably want to subscribe to it with OnTriggerEnter so this way you know you're inside of the collider
Well, ideally the collider and the ladder trigger are the same thing.
What do you mean by this? That also doesn't really answer my question
as long as you're subscribed you know you're inside of the collider
otherwise it seems bounds is the idea, otherwise nav's idea of backface checking but it means your ray must intersect completely
It currently works similar to HL2 in my case. You can either attach yourself to the ladder if you interact with it from a distance, or by jumping/touching it. That's just the way it is designed, and I only need the simple operation of detecting what entity the player is looking at, including if they're inside the collider.
It's not a matter of debating the design, but finding ways of raycasting from the inside of a collider and hitting it.
in source players are not inside the ladder collider
im making a scene manager but i dont want to add each scene a manager what should i do
They are, but it doesn't matter.
no?
hi guys so I'm trying to make my character go up and down the Y axis in unity and the code works but it doesn't move inside the game pls help me.
Here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPersonFly : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jump!");
}
// Fly ??
float moveSpeed = 40.0f;
float dt = Time.deltaTime;
float dy = 0;
if (Input.GetKeyDown(KeyCode.Alpha8) == true)
{
dy += moveSpeed * dt;
}
if (Input.GetKeyDown(KeyCode.Alpha2) == true)
{
dy -= moveSpeed * dt;
}
// float Vertical = 0f;
// if (Input.GetKey(KeyCode.Alpha8)) Vertical -= 1f;
// if (Input.GetKey(KeyCode.Alpha2)) Vertical += 1f;
//
// transform.Translate(new Vector3(Vertical * Time.deltaTime, 0, 0));
}
}
they are snapped onto the face unless im mistaken
You are mistaken. There is a trigger.
i am aware there is a trigger
Good. That doesn't have any relevance to the problem. I will try to search for the answer elsewhere.
okay..
but i wanna add the functions of the manager to buttons which is in main scene
(was relevant)
sure, why not? Whichever scene you want the manager in you tag it with DontDestroy, so next scene you load it will carry the manager with it
{
if (slowedDown == false)
{
Time.timeScale = time;
slowedDown = true;
Debug.Log("sloweddown");
}
else if (slowedDown == true)
{
Time.timeScale = 1;
slowedDown = false;
Debug.Log(slowedDown);
}
}
(This is inside an update function)
if (Mouse.current.rightButton.wasPressedThisFrame)
{
SlowTime(0.1f);
slowedDown = false;
}```
Why dosn't the debug message show up in my console when i right click? The time slows down correctly but for somereason i dont get the debug message
but if you have references to the main scene on scene change it will lose them on the manager
so if each scene has unique data for the manager, then maybe making a unique manager for each is the idea
but i cant add the functions of the scene manager that in another scene
right, so manager each scene it is, otherwise you need to dynamically link it all at runtime
ex. change scene -> level scene gameobject on awake call thes scene manager and binds itself to it
I wanna add a function of the scenemanager in game scene but in gamescene i have no scenemanager game object. So i cant add it manuelly that is the problem. is there any good solutions besides adding each scene a manager
i didnt understand
what needs to be added to the scene manager on scene load
when i load another scene i want to use the same scene manager for the other scenes scene changing button
wdym
public class SceneChangingButton: Monobehaviour
{
private void Awake()
{
SceneManager.ChangeButton = this;
}
}```
that's the dynamic solution for 1 scenemanager singleton with DontDestroyOnLoad
what does changebutton mean
"other scenes scene changing button"
ohhh
Idk, any data you wanna bind, it needs to be done on scene load in awake. Just a solution, there's many others
can somebody help me on this issue pls?
but i have more than one button in a scene
well. gotta do it for them all then
i want to add manually
or, just make a scene manager on each scene and drag those references on the inspector <--- easier
ok ill add scene manager to all scenes
can i ask one more question
i want to make a button from a sprite
but when i add component i cant click it
should i use ui for it
or is there any other way i can use
just sprite
you need to look into how to raycast a spriterender
UI stuff already includes raycast logic, but if using UI doesn't make sense then you probably shouldnt
anyone?
your unit logic seems fine so something else is off
this code doesnt actually move anything, its just modifying local floats
oh
so to make it move my character I gotta call it inside? I thought I just needed to drag and drop the code on it sorry
i want to add a text on sprite square how can i add
Create a TextMeshPro object, likely as a child object of it, and position it where you want it to be relative to the sprite
im not fully sure what you mean by this, but your code is just not moving anything. the only part which could move something is commented out.
if you weren't aware of this, you should really start with some c# basics
Anyone knows how to chain multiple formatter together in smart string? For example, {0:formatterA():formatterB()} something like this.
what is a smart string 😆
What's the use case
I think they mean string interpolation
you can use string.Format() to replace named placeholders such as {0}
otherwise yea with string interpolation you can provide a ToString() format str like you did kinda
If its mad just do .ToString()
$"{thing.ToString(Func())}";
Something like "Damage is {attack:math(+3.5*5):format(0.00)}" to display the actual calculated damage in the localization text.
then you do need string.Format()
Unless the unity localisation can do extra functionality
https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/Smart/SmartStrings.html#formatters
the built-in localization can already do a single function. I made {attack:math(+3.5*5)} and {attack:format()} work. Not sure if it supports chained formatter natively.
Yeah like Rob said something like:
string.Format(GetLocalizedFormatstring(Key), math(numbers))```
You could do the math in parenthesis, then do a .toString() formatter
Can not find the syntax in the documentation.
$"Damage is {(attack + 3.5*5).toString("0.00")}"
string.Format() is easier as you know what you are getting
"Damage: {0}, other shiz: {1}"
and as its ordered it works good in translations
string.Format is C# right? I was trying to avoid coding directly to allow designer/translator to do that inside the localization file.
the {0} tokens go in the actual string
The code would be separate from what the designer makes
they do have to know what they stand for
when ive used gridly i leave an example in the context column
passing {0} directly meaning {0} is the calculated result? Which mean I need to hardcode the calculation inside code?
yea in code you need to provide what {0} is replaced with
if you want actual maths in string thats a whole other ball game
I recommend not trying to do that
You can create a template scheme of your choosing but you'll need to write code to parse and replace things
I have already achieved that by writting a custom formatter for smart string.
Just not sure if native smart string can have chained formatter
i did it like that but the sprite is front of it
I'd like to be able to visualize systems when I'm making new systems or doing big refactors. Do yinz have any way you like to accomplish that? Any good tools?
anyone know how to combine multiple splat maps together in a .shader file so you can add more than the 4 RGBA layers to your material? this is what I have so far as you can see in the screenshot but I'd like to add more layers but I need another splat map so that I have more color channels available to assign as a layer.
#1390346776804069396 is the place to ask because you have to solve the problem of how to know what splat map to sample in the shader as well
you've mentioned colliders to raycast, what about going with a tilemap approach instead? I'm just worried about performance issues down the line when I have 10k tiles with colliders on em
so silly question but is there a way to keep two value types from different class to equal each other without needing to call it in update each frame? ie keeping the float playerHealth to equal the CurrentHealth in the other playerHealth = StatsController.CurrentHealth;
nope, you have to either copy the value when the other changes or keep it in some class that both objects can reference
float is a value type so always copies
this feels kinda inefficient though
yea it is so you should stop 😆
its also going to give you bugs and problems, how do we know what value is the "real" one?
have this data be kept in a class instance that multiple things can reference
then its a non issue
This yearns for properties
fair, just noticed it while trying to rework some old code from my first game
had no clue what i was doing even though this was only 10 months ago
if that is "bad" for you look what i've got in the other class (luckily only called once on start)
with properties you can do
PlayerHealth { get => StatsController.CurrentHealth; set => StatsController.CurrentHealth = value; }
Then you can touch PlayerHealth like it’s a field but it’s actually two functions in disguise that just point to/forward the statcontroller value
does this update PlayerHealth if CurrentHealth was changed? and what about vice versa where if PlayerHealth was changed would CurrentHealth update?
a property with a get and set is not a variable
its a fancy getter and setter function
it isn't? TIL
With this PlayerHealth wouldn’t actually be a value. It would look like one when referenced in code but it actually just points towards another value
but is used like it is a field
auto properties are the same but have a auto made backing field they set and get with
what's the => do in this case
Properties are a pair of functions in a trenchcoat pretending to be a variable to get into an R-rated movie
short hand for
get {
return foobar;
}
You define a get for what happens when you want to read from a property and you define a set for when you want to write to a property
does it matter that it's declared at the same time as when the reference for StatController is in the class? or no since it's not a var
the getter and setter are just functions so it can do stuff with a class field (and other stuff a function can also do)
public float SecretFloat => secretFloat;
private float secretFloat;
It isn't really "declared" anywhere. It's not a variable. You define the functions that get run whenever the property is accessed or modified. If the StatController is initialized before either of those are called, it won't be a problem
Remember there’s only 1 actual value being stored in this suggestion, the one in StatsController
if you talk to PlayerHealth in anyway you’d actually be talking to StatsController.CurrentHealth
We solve the problem of you syncing 2 values by just having 1 value accessible from two different points
back to the actual topic, you can keep the data in a class instance and use it via that or declare a property to "aid" in using that to avoid doing that weird copy in Update() @rough granite
check the docs for more info about properties if needed 📖
will do, another question though SO's can there only be one instance of them in a scene like static classes or can i make multiple instances?
Each file on disk you've made from an SO is one instance of that SO
it lives in a file rather than in a scene
and you can reference a scriptable object file as much as you want
so if i wanted to reference a SO class would just giving it's name work or do i need the specific instance :?
damn why in the update ?
err
cause this was like week 3 of learning to code :/
You would need a reference
I sense miss understanding 🙏
Probably.
probably lol
3 week???? of learning code ? then fine , don't mind me 
sorry
well this was ages ago been about 11 months since i started now but trying to fix all my mistakes
scriptable objects are a way to define a new asset type with data you want, just like a material or model or texture
oh I see
SO what a great creation 
what would the best way of having a single instance class that doesn't need to be strictly referenced by using, but can be used by many different classes (and not static) [SerializeField] StatsController StatsController;
Sounds like singleton
totally had the wrong idea of them then whoops :/
is this another Inheritance type?
you can probably just have a normal class to hold these stats
do you mean like no inheritance :?
If all it does is store some numbers it does not need to be a MonoBehaviour or be created as a scriptable object
^ the singleton pattern is good but more applicable for a MonoBehaviour
Perhaps a class to hold stats is used AND you have a reference of it in a singleton game manager?
it does have functions in it that get called but yeah mainly stores values that are meant to be accessed easily
but does having it as a basic class limit it to one instance :?
no?
:/
whut ?
Learning c# only with unity can lead to these weird thoughts 😆
MonoBehaviours are base classes with a couple layers of inheritance stacked up on it
shh i learnt java first then skipped learning straight c#
base class -> Object -> Component -> Behaviour -> MonoBehaviour
oh
c# properties are basically microsofts solution to the getter and setter functions java loves soo much
learning something new
guys, can someone help me? I am making my first game, I added a Character Selection screen, but when I load the player character into the game, while the character is walking it changes back to the default skin. How do I make the animation change according to the skin selected?
i like this advice
do you use sprite renderer our sprite resolver ?
i am using sprite renderer
then you need to change it if you change the default skin then you need o change the clip to as you are using sprite renderer
the best way is using sprite resolver + sprite library
i am working on it so i can't help you more 
okay, I will try! Thank you so much!
thank you for your time
Me handing in my exams like:
what have you send ?
nawh :c
SO! Question: You guys think it's a good way to learn with books, courses or just start something and try working from there
A gif! Squidward kissing a piece of paper while looking completly exhausted
it depend but the best ways is both together , learn something in the book and try to apply it.
theory and practice is 2 different thing
Hey! Do you guys know of any great sources to not just learn about the SOLID approach but also understand how to develop your own logic to implement it? I really like it but having a hard time coming up with it myself.
Experience
You need to understand how it work then you can implement it by yourself
Tuto is a way but in code, you have a lot of way to archive a fonction
Some more optimism, other more easily or shorter
There are some YouTube videos that cover SOLID in details, but perhaps don't fixate on them too much. Don't make them the goal. Instead understand what they imply and how they can help make your life easier.
How do I gain the experience if I don’t know how to implement it in the first place haha
Like I know the premise
And separation of logic
But it’s hard to visualize it and make the flow chart and diagram🥲
when you try and implement something what are you thinking?
I learned that so far, I understand the flow and everything, I only have a hard time designing it myself
“What would be the most ideal approach for this”
And then everything I learned the past week mixes in my head and I’m like “should I use a scriptable object for this? Or an interface? A static? Composition inheritance instance?” And then I don’t know which to choose
Well, this will come with experience. It's not something you can learn by reading or watching tutorials. Reading other people code can help, but the best way is trial and error while remembering the solid and oop principles.
The rule of thumb is start simpler. Only introduce complexity if it's really necessary.
not that my advice is the best but i think thinking of what you want to implement in a real world sense be it the physics or well whatever then putting it into practice in code rather than thinking of what it should be directly in code
While I try I keep doubting myself and I’m like “wait is this true separation” “what actually needs to be separated” “could this be combined without violating the system”
But if it’s truly just experience I guess I’ll have to crawl through it for now🥲
One example is jumping and fall damage logic that i was stuck on and running and stamina drainage, I wasn’t sure if to separate them or not but ended up making an interface IStamina then a script to handle the logic and finally a system script that “bosses it”
So first plan then think of the logic and then code
You should remember that there's no perfect code. Even the most experienced dev wouldn't write something perfect. Just write something that works. And iterate on it as you go(if there is a need).
But I often gets stuck on the digram alone🥲🤣
That’s the thing, I wrote a base movement system that worked perfectly but it got so messy with everything in one script dependent on each other and I got so overwhelmed that I dropped my project for a week because I knew that there is no way this is how I should do that
And then I learned all the advanced techniques and OOP principles
And it’s much less overwhelming this way I really like how organized it makes it in my brain
yeah for example i spent a few days learning orbital mechanics for my game, and instead of just jumping right into the code i researched on things like keplers laws, and newton's gravitational laws.
Well, then you skipped the "iterate on it as you go" step. This might involve refactoring to make the code easier to read, debug and extend.
Ohh wow! You went as far as learning the physics for it too
Yes haha I didn’t really know any advanced techniques before this week I just wrote everything into one MonoBehaviour lol
it didn't go well 😭 i couldn't get them to do proper orbits (though i only spent like 2 hours a day for a few days)
I feel you on that, I don’t even wanna touch physics or math logic for now🤣
annoyingly enough it's hard to find just straight physics equations on google
It takes me two hours just understanding reading code that implements physics calculations lol
oh sorry I thought the .shader script would be considered code I'll make sure to ask in #1390346776804069396
That’s true🥲
Would using GPT for SOLID logic only help?
Like spitting code at me to iterate over
Basically just proceed with the implementation taking into account the things that you learned.
If you're stuck on something specific, you can always ask for ideas here.
Oh I revamped the script altogether haha I copied all of them into legacy dupe scripts and I’m re building it from the ground up😅
I made like 13 scripts that handle things separately using interfaces
I love interfaces tbh haha
There's no such thing as "SOLID logic". If you really did learn these principles, you should know that they are very abstract things and don't force and specific coding pattern on you.
what's SOLID logic :?
I meant like formula haha
Or structure
Solid don't dictate any of this.
I watched in a video that it was said in a way of like “not violate the rules of the solid system” something among those words
They're just guidelines to keep in mind when you implement your own structure.
Yes guidelines haha
I like it, it gives me like a base to go off of
Something to follow
So I don’t just free roam and make a mess
oh is this why people put an I before their interface classes?
Next I really want to learn Events and State Machines because I believe they will be helpful too
That’s just to distinct that it’s an interface haha
I for interface
No. That's just a naming convention. Unrelated to SOLID.
well no i know that but i mean is this the silly principle that people use for why they have silly naming conventions such as the I for interface and _ for private variables or whatever
I like the I but dislike the _ 🤣
oh i see i miss read what the I stood for
It lets me know what the blue print is and what no to attach to game objects
At first I disliked interfaces because I was like “I really need to make a whole script for like 10 lines of code?” But then I saw how much it organized everything
Does anyone use Yarn Spinner here? How can I trigger an interaction dialogue using an action key without running it at the beginning of the game? Just played around with it yesterday and just started coding last week, any basic help would be appreciated.
Probably best to just ask in their server https://discord.gg/r92DjJ6ehX
Thanks!
i just finished learning vector3 and raycasting what should i do now
try making something with it to prove you understand it
i've made many from scratch
I just want to know what i should do after that, or what i should learn.
rather than studying random topics, consider going through a structured course that teaches you the concepts you need to understand in a structured/ordered manner such as by using the pathways on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Make a game you want to make and learn whatever topic ends up being necessary for making that game
It's really big to learn "on the fly" imo
motivationally speaking
Hi guys, could there be an issue with the representation of eulerAngles in code?
I'm trying to limit the rotation on the X-Axis of my object by converting the presumed new rotation to euler, check if the rotation on X-Axis is greater than my desired maximum and clamp it. But when putting the values to the log, I can see that the value is increasing up top 90° and than decreasing, while Z is flipping from 0° to 180° whenpassing that point. Inspector gives me values between 0 to 180.
float XInput = inputVector.x * _config.RotationSpeedX;
float ZInput = inputVector.z * _config.RotationSpeedY;
Quaternion rotation = Quaternion.AngleAxis(ZInput * deltaTime, motor.CharacterRight);
rotation *= Quaternion.AngleAxis(XInput * deltaTime, Vector3.up);
Vector3 tmpRotation = (rotation * currentRotation).eulerAngles;
Debug.Log("Quat to Vector3: " + tmpRotation);
// Never reached since my MaxAngle of 150° is never reached
if(tmpRotation.x > _config.MaxAngle)
{
tmpRotation.x = _config.MaxAngle;
}
currentRotation = Quaternion.Euler(tmpRotation);
Quat to Vector3: (89.03, 232.89, 0.00)
Quat to Vector3: (86.19, 52.88, 180.00)
Using Euler angles for this is a nightmare and a bad idea
You cannot generally isolate a single Euler axis and do logic with it. All three axes are inextricably linked and cannot be treated in isolation.
Any suggestions how to limit X-Axis rotation then?
I know that Quaternion multiplication isn't cummutative, so maybe reversing the order gives me the same values as the inspector
Do not try to rely on Euler angles
Seriously
You're setting yourself up for sadness
Yes, diligent and thoughtful use of Vector3.SignedAngle and Quaternion.RotateTowards
Maybe defining a max rotation using Quaternions and comparing via Quaternion.Dot?
_maxXRotation = Quaternion.AngleAxis(MaxAngle, motor.CharacterRight);
Oh, RotateTowards could be helpful, forgot about that
Does anyone here have a 3d player movement script for unity I could borrow?
doesn't need to be anything special, just something that works
You could use Unity's own starter assets controller
ya I tried using it but I couldn't figure out how to get it to work 
and please don't crosspost
Crosspost?
posting the same question across multiple channels'
Hi everyone, I have a problem with my code. It doesn't detect the name of my other code. It says it was not found.
Then that's either not the class name or its in a different assembly definition (so this class cannot access it)
Show the declaration of the other class
Looks like a different assembly
It looks like it's in a different assembly
Looks like CarControllerNPC is not detected as a class in the project (based on the colour of stuff)
probably "miscellaneous files"
i'm having this issue and it driving me insane!!! so i'm doing a boxcast for placing objects but for some reason the hit.point is slightly to the left?! here's my code
Physics.BoxCast(Cam.position, heldObject.GetComponent<MeshRenderer>().localBounds.extents, Cam.forward, out RaycastHit hit, heldObjectRot, RaycastDist, placeLayer)
but weirdly spherecast works?
Use the physics debugger and see what's going on
https://unity.huh.how/debugging/physics-debugger
Also it is generally concerning to me when people name a mask "layer" 😭
btw it's what most tutorials i've watched call them, you probably should call them mask idk?
you miss understand, a mask is a set of layers you want the boxcast to use
i looked at the physics debugger and the debug view is what i want but for some reason the hit.point isn't?

the cube in front is where it's been placed.
It's unclear where the hit point would be from that view, it looks like it hits the ground completely flat
Maybe it would make more sense to you if you placed the cube at Cam.position + Cam.forward * hit.distance
Which would be the centre of the box hit position iirc
ok that worked but that seems like it could have issues if the hit.point is offset?
I'm not sure what you mean
i.e there an uneven ground and the hit.point is slightly to the left which could make the hit.distance be way off!
I don't really get what left or right is, the box is casted against a surface in the direction, and the distance it travelled can be used to get the centre of the new box
why do you think the hit point is offset
how are you spawning that cube
Finally got the rotation clamped, forget Euler and just cancel Input if necessary
private void SetRotation(ref Quaternion currentRotation, float deltaTime)
{
float XInput = InputVector.x * _config.RotationSpeedX;
float ZInput = GetZInputClamped();
Quaternion rotation = Quaternion.AngleAxis(ZInput * deltaTime, motor.CharacterRight);
rotation *= Quaternion.AngleAxis(XInput * deltaTime, Vector3.up);
currentRotation = rotation * currentRotation;
}
private float GetZInputClamped()
{
float input = InputVector.z;
if (input == 0f)
{
return 0f;
}
float angle = Vector3.SignedAngle(Vector3.up, motor.CharacterUp, motor.CharacterRight);
if ((angle > _config.MaxAngle && input > 0f) ||
(angle < -_config.MinAngle && input < 0f))
{
return 0f;
}
return input * _config.RotationSpeedY;
}
i am literally placing the cube at the hit.point which is weirdly one, off-center and two, in the ground so i have to elevate it!
hit.point + (hit.normal / 2)
homie
It's likely to do with how you're placing the cube rather than the hot point
any chance the amount your offsetting the cube vertically also happens to be the same amount its going sideways? 😛
how?! obj.position = hit.point
Are you perhaps placing it not relative to the hit point or the hit point with some offset?
Why are you dividing the Vector of hit.normal?
nope i checked, that was my first thought.
because rn, the hit.point is not at the center of the where it should be thats the entire problem!
If that's the default Unity cube, its pivot point is at the center of the cube. So of course if you place the center of the cube at the hit point which is at ground level then the cube will be placed halfway in the ground
i haven't seen any evidence of the hit.point being wrong
look at the picture above.
i did! but i'll do it again
if (Physics.BoxCast(Cam.position, heldObject.GetComponent<MeshRenderer>().localBounds.extents, Cam.forward, out RaycastHit hit, heldObjectRot, RaycastDist, placeLayer))
{
Debug.Log(heldObject.GetComponent<MeshRenderer>().localBounds.extents);
if (Vector3.Angle(Vector3.up, hit.normal) < 75)
{
Transform obj = heldObject.transform;
obj.SetParent(null);
// obj.position = hit.point + (hit.normal / 2);
obj.position = Cam.position + Cam.forward * hit.distance;
obj.rotation = heldObjectRot;
heldObject = null;
isHolding = false;
}
}
cool
i haven't seen any evidence of the hit.point being wrong
you are offsetting it wrong
wait huh
obj.position = Cam.position + Cam.forward * hit.distance;
what do you think this is doing
just scroll up please! it was a fix someone suggested i have already said i don't like it.
I still don't get why you use hit.normal / 2.
hit.normal gives you a direction, you need to define a distance by multiplying, i.e. at least the half-height of your cube
Your suggestion didn't make any sense, and your code misunderstands what the hit point is
that is what i was planning on doing but the issue is the hit.point being off center. (slightly to the left, spherecast is fine tho)
hit.point is not off center.
but mine is!
nope
It's not off centre, the cube hits the ground and whatever the first place on the cube that hits is what's returned
Your screenshot had the cube hitting the ground flat, so that point could be anywhere on the bottom face
You are doing a BoxCast, so the first part of the box that touches the normal sets the hit.point
I think they expect the hitpoint be at the middle of the boxcast on the ground, at the red X. But it's at the blue X which is an arbitrary point because the boxcast hits the ground flat on
Which is a large area that you're just saying is off centre because you don't understand
Unless im tripping I haven't seen any of their code that would actually put that cube in that spot based on that hit point though?
i agree with what your saying just curious
Is the cube a child and perhaps the parent is being placed ?
I would use BoxCast to see if something fits between stuff, not to spawn objects.
Do a Raycast and then an Overlap check for your box size
My suggestion gets the centre of the cube. If they wanted the centre of the face that hit that's also possible, but at this point I'll be leaving instead
then why does spherecast.point work perfectly fine.
Because a sphere doesn't have a flat face?
Because a sphere has a smaller / not flat surface
The sphere hits exactly one point, at the red X in the picture
no i just want the center of the cube.
oh right the normal offset would do that ye, forgot it only needs half a m up
Then my suggestion was that.
The hit point isn't assigned by you but rather the physics system. It's value is that of where the point of contact was made. How you choose to use the data would be dependent on your needs. The point of contact (any point that makes contact - any point) is where the contact was made. If you're wanting the center instead, perhaps try raycast rather than box cast.
🤦♂️
(i just wanna clarify even though it's totally valid to want the centre of the cube, that's not what the point of the hit is, hence confusion)
This is the centre of the cube for a boxcast
@patent wedge Do a Raycast and then check with Physics.OverlapBox if your Box fits at the hit.point.
If it doesn't collide with anything, spawn the cube
i'm just gonna stick with this. unless there's any better way.
i'm still confused what exactly is hit.point? and why is hit.distance not the distance from the origin to the point?
Any point where the two objects make contact.
if your driving and you hit someone on a bicycle the hit.point is where the car contacted the bicycle, not the centre of the car
Distance is the distance the cast travelled, not the distance to the hit point
now if you drop a crate off a building onto the street multiple "points" on the bottom of the crate might hit the concrete at the same time
in this case the crate hit this corner of the ground "first"
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RaycastHit-distance.html
In the case of a swept volume or sphere cast, the distance represents the magnitude of the vector from the origin point to the translated point at which the volume contacts the other collider
Thx everyone for your help.
hit.point is the part of your cast (a box in your case) that touched the normal first.
But your box has a huge flat surface that hits another flat surface, so the first contact spot is floating in the noise region of your floating points.
Just rotate your BoxCast 45° on X and Z, you will get the same point every time since the tip of your cube always faces down
Use a Raycast+OverlapBox or something
I am pooling a bunch of meshes in and out of player view, I decided to disable/enable collider and mesh renderer, but as I do so but spikes seem to be bigger and profiler generally more dense on low amplitudes.
Is it generally a bad idea to disable/enable or am I just doing something wrong elsewhere?
Toggling the active state is better than destroying/ creating.
Why are you toggling those components though? Just toggle the root/ parent gameobject
the root component runs other threads for calculations even while pooled away so i cannot, i just dont want the player seeing it coming back to view mostly and maybe get a slight optimisation in case unity renders things that are out of view
for collider im scared that i will spawn something that moves on it and it will roll away for no reason (while the mesh is reshaping) xD
this is occlusion culling which Unity does for you
no no, it does my calculations while pulled away, i.e. pcg generating next heightmap etc, thats why i keep the parent active. when its back into view for reshape i make the mesh visible again, adjust vertices, calculate bounds etc
i was just wondering if its better or worse to actually use disable + enable. the implementation doesn't really matter tbh
better or worse than..
Pool system then ?
It better to do enable + disable than create/ destroy as it cost more
You can also load everything then disable it after, so you will not have the frame lag because of shader calcul
I already have a pooling system, when I pool them I disable when I unpool and modify enable
the alternative is clipping the camera so the player doesn't see that im moving chunks around
Of the two which is worse? The colliders or renderers? And enabling or disabling?
The two components (relative to name) sound like they would be doing some bit of work when disabled and enabled.
I'm assuming you've verified the performance with the Unity profiler.
They will do work anyway after unpool because renderer will have to display new shape and collider calculate new collisions. But does disable/enable have significant overhead?
Check the profiler
yes it's worse to disable/enable, but I wonder if it's my fault somewhere or this is default behavior
like, do others suffer when they do this?
it's something you're doing
Check with the profiler instead of guessing.
What do you mean by out of view btw? Unity always uses frustum culling so disabling renderers outside the frustum wouldn't do much
actually that's helpful to know!
Colliders, so they may be getting removed from the physics simulation
Not that the frustum check is free but I would be surprised if the one unity does (in c++ I assume) is slower than yours
im not doing it to optimise im doing it to hide moving it in from the player for that 1 frame cz it looks a bit awkward, but i care about fps ofc so i ask 😄 im good now though
thanks
kinda gonna rush it because its for my thesis, I think im overthinking the smallest things
I don't quite understand what you mean by that 1 frame thing but whatever, good luck
when I unpool many chunks, people can see them kinda move from poolposition to their position for some reason. Even though it's numerically a transform.position = new_position, for some reason it's a visible change like movement. disabling/enabling or camera limiting fixes that
Never heard of that happening. If you immediately position the chunk when you enable it from the pool (not in that chunks update or something), there shouldn't be a frame rendered in the wrong position. You should look to actually fix that issue rather than working around it
I am talking without enabling it, the pooling is just moving it out of view and bringing it in when needed. There is no issue I think, it's just unity processing too much
I again don't know what you mean
also pooling by moving out of view is quite odd, generally you would just deactivate the object so it would disappear from all the systems (rendering, physics etc.)
Is there any way I could get someone to watch me code and explain the basics? Complete beginner and YouTube tutorials aren’t doing it for me
only for £££/$$$
Alright thank you
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i am watching a tutorial from a couple years ago and i am running into a problem with this line of code. How do i fix this????
it doesnt like the top line
i think u should say KeyCode.D in the brackets instead
have you googled that error
yea, was too confusing for me
i started yesterday
You are using the old input class, unity made a new input system. Your project is set to use the new one.
go to project settings > player to change it back to the old one OR learn the new input system (recommended)
Input code differs between the built-in Input Manager and the Input System, and changes are required.
we need a bot to auto reply with these links
add support to the feedback for adding a bot command for it
https://discord.com/channels/489222168727519232/1400500402730045654
yo guys how do i solve this
!install
- Make sure you have enough space including on
C:drive. - Check that it's not being blocked by antivirus/security programs.
- Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).
If you still have issues, perform a clean install in another location:
- Install the Hub and Unity in a non-system drive or a clean new folder in the root of
C:drive. - Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
when i use the toggle box, the glow prefab switches intensity, but only when i select it in the project window, and it does not update the glow on my other prefab, even though it does when i change the intensity manually
what is going on?
also im trying to get the toggle to stay check wehn leaving the scene but im failing so far