#💻┃code-beginner
1 messages · Page 546 of 1
we could if you posted some code 😉
📃 Large Code Blocks
📃 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.
hi guys, im trying to make a quick time event to make my character crawl, i got the animation but i dont really know how to make it stop and wait for a qte, or even making a qte, any tips?
i am assuming you mean the OnCollisionEnter method, where the knockback is located
yes for whatever reason the knock back isnt workign
i followed the tutorial exactly
is the OnCollisionEnter being called, you could find that out with a simple Debug.Log on the first line.
Debug.Log("Collided with " + collision.gameObject.name + " with power up set to " + hasPowerup);
does that ever run? ^ if not its b/c if (collision.gameObject.CompareTag("Enemy") && hasPowerup) one of these aren't true
thats what i have also but that doesnt show up either
add the debug right after the oncollisionenter
u should always do this to test anyway..
//log
if(extraCondition){
//log
}
}```
before the if statement?
u want to know if OnCollisionEnter is being called at all
then u move on to the next step
The golden rule: Hang On, Is Anything Happening At All?
well, more of a golden question
aka Dude, Where's My Call?
plugs in Mouse, aight guys fixed
microsoft support: Have you tried restart computer?
i just got "Collided with island with power up set to false" ... fuck
oh man, this is a good one, actually
there you have it as Spawn said, your OnTriggerEnter might not be called because the bool is never set to true
waiit where?
private void OnCollisionEnter(Collision collision)
{
Debug.Log("This will be logged regardless if its an Enemy OR if hasPowerup is true");
if (collision.gameObject.CompareTag("Enemy") && hasPowerup)
{
Rigidbody enemyRigidBody = collision.gameObject.GetComponent<Rigidbody>();
Vector3 awayFromPlayer = (collision.gameObject.transform.position - transform.position);
Debug.Log("Collided with " + collision.gameObject.name + " with power up set to " + hasPowerup);
// this one should not run if powerup is false ^^^
enemyRigidBody.AddForce(awayFromPlayer * powerupStrength, ForceMode.Impulse);
}
}```
in unity i moved the debug.log to before the if statement
but if u moved the debug up below the oncollision and it worked. that means yea ur condition isnt being met to run the rest
its still in the oncollision i just moved it up
Hi, I don't really get why AtRest is becoming true when Vector3.Distance(transform.position, targetGridPos) is 0.8 like on screenshot when in the condition it says it has to be less than 0.05
I struggle to understand why after I move with smoothTransition = true my character is unresponsive (engine is working as expected)
Code: https://paste.myst.rs/stcpacv6
Check comments in the void MovePlayer() for more details
In the screenshot u can see relevant logs,
a powerful website for storing and sharing text and code snippets. completely free and open source.
thats not 0.8
nah, it is
is it? 👀
it's the French/German/etc. decimal separator
why the whacky ohh
This isn't logging the res variable.
yeah we use that thing here
do you have "Collapse" turned on in your console?
Today I Learned
That would cause identical logs to get combined into one
we had a really funny issue in here where it perfectly concealed an off-by-1000 error
2,000 (US) became 2,000 (German)
the latter is 2 :p
i am still so confused
yep, when turned off it shows
"AtRest: false" is what I'd expect to see here
i dont know what to do
check for the logs, did they appear?
nope
then the function is not running, find out why
the problem is i dont know and ive followed the tutorial exactly
What function is it in?
im just completely restarting from scratch ill let you know if the same thing happens
"AtRest: false" is what I'd expect to
"throw it out and start over" is not a very practical debugging strategy
i know its not but when i followed a tutorial to a tea and cant firgure it out
does this block of code ever get called?
if (other.CompareTag("Powerup"))
{
hasPowerup = true;
Destroy(other.gameObject);
}
if not then you need to check if one of your colliders is a trigger and if they have the right tag
send the link of it
gotta see if script is running at all
I fixed it, i didn't assign the Clone_Skill_Controller to the clone 😭😭😭😭
that was the problem
thank you anyway
Thank you
screw log spam
teach me how to make breakpoints not break
(not really im busy rn i just want to be able to use them)
Thank you so much, my prblem was in assgining the script to the clone and that's it
Rider's work pretty reliably
only got vsc
then consider switching to a real IDE that is less likely to randomly break
so true bestie
I had middling results with VSCode
Sometimes it worked, sometimes it just kinda...got stuck
ill make sure to throw nvim with the fanciest rice on my new gentoo minimalist install
does this block of code ever get called? #💻┃code-beginner message
or instead of shitposting, you could download visual studio or rider, both of which are actually supported by unity and are far better than vs code which tends to randomly break for no discernible reason
if you are on linux you only have VSC and rider (VS not supported), I heard the latter is good
last time i tried visual studio it was a laggy pain (and that was on my main pc which is way beefier than my thinkpad on which im actually devving)
unity itself is already straggling it by the balls and only doesnt immediately freeze my pc because i threw in like two rams worth of swap on it, so i dont think adding vs on top will help
also, linux
i am now a uh
am gonna try rider tho
gray knight for VSCode
not a full-on white knight
i think it's ok
Rider has been delightful
keep in mind rider is non-commercial use only for the free version
yeah vs code is generally fine, but with unity it tends to break quite often which is why i avoid it and recommend others do so.
rider is and always has been super nice to use, and vs is somewhere in between. though i will say it was super slow when i had resharper installed for it, which is ironic considering rider itself runs like a dream
as if that mattered for me 
(the context being im too dumb to actually release a game)
well if you do, you would need a license
rig
VSC has worked so far for me, I have not had anything bad happen yet
I have not tried rider yet
I've seen a lot of people with weird issues getting the .NET SDK to work in VSC
it'll just...not download
After that hurdle, it was pretty smooth sailing. Debugging was hit or miss
i think i had that happen like once
was p easy to resolve tho
It was mostly fine for me, except when it decided to re-download while on an airplane
(several times)
I couldn't convince VSCode to use a manual install
pacman -Syu microsoft_gigapackage ftw
do wonder how it's gonna go with portage tho
collapse ur logs. only time it spams if its a different log. not as good as breakpoints better than spam tho
nah sudo pacman -S dotnet-sdk
even better
debug mode in inspector the way to debug values imo, 🤪
ermmm you must -Syu because system package stuff??? didnt u know???????
works for me
yeah tbh i dont get it either
i just do it out of used-to-ness
also side tangent
the fact i can sudo !! is fucking lovely
Undertale top-down part in Unity 2D 😄
I often bounce between Rider and VSCode since Rider doesn't run that great with Unity projects for me regardless of the settings it has (and my pc is high end). Runs perfect for normal .NET projects which is the confusing part. Lately I've been leaning more toward vsc just so I can hop files quickly. I do prefer Rider though, just not when it cuts into my hours 
use #1180170818983051344 to show off your work
oh, ok, sorry 😅
so im back to where i was i didnt add the knock back but the consol doesnt say that the collision method should be called https://paste.ofcode.org/Nmbh2FDAmwReynYsTZWaMM
you probably want that comparetag you originally had, make sure your powerup is a trigger and has the specified tag on it
i completely redid everything and now it works isnt programming so much fun
It is
i love working on something for over an hour have it not work then when you start from scratch now it works
that is why you debug so you don't have to do that
By rewriting it, you eliminated the bug introduced by mistake
how do i enable and disable a camera with input?
two separate problems!
- receiving input
- disabling a camera
set its enabled property to false
set it to true!
you could do cam.enabled = !cam.enabled;
this switches it back and forth
Set it to whatever it currently isn't
The missile knows where it currently is...
ohh ok lemme try that
im doing some unity learn challenges and thats the one i got stumped on
ok turns out input was not done already
its more complicated than i thought
how so?
could yall explain this to me like if i were 5 this wa the solution listed on the problem
if(Input.GetKeyDown(switchKey)) { mainCamera.enabled = !mainCamera.enabled; hoodCamera.enabled = !hoodCamera.enabled; }
all that code does is toggle the camera on and off based off an input
similar to a toggle boolean
i see
Whenever switchKey is pressed, main camera and hood camera's enable states are set to whatever they currently aren't
GetKeyDown is true for one frame at the start of a press
GetKey is true during a press
GetKeyUp is true for one frame at the end of a press
actually it is a boolean
Super simple script:
public class TestScript : MonoBehaviour
{
private Camera _camera;
private void Start()
{
_camera = Camera.main;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
_camera.enabled = !_camera.enabled;
}
}
}
would that code work if it were applied for other things? without the camera things of course
so it is the exact same as a toggle boolean
Whatever you put inside that if statement will run
If you put Application.Quit(); in there, the game will exit
sure if you toggle a boolean

huh didnt know that was a thing
Hence why I said this!
You don't have to use a special GetKeyDownToTurnOnACamera method
Most of programming is just deciding:
- When do I do this?
- What do I do this to?
wow, i learn more every day
I do this:
- When space is pressed
I do this to:
- The camera stored in the
mainCameravariable
Is anyone able to tell me why my crosshair object refuses to follow the mouse position on the X and Y axis? Cannot figure this out for the life of me but I believe I am using the right ideas just not executing correct.
Vector3 mousePos = Input.mousePosition;
mousePos.z = distanceFromCamera;
Vector3 worldPos = cameraMain.ScreenToWorldPoint(mousePos);
crosshair.transform.position = new Vector3(crosshair.transform.position.x, worldPos.y, worldPos.z);
its way simpler when put like that
thanks so so much
why are you using the crosshair's existing X position?
indeed! that's something you'll learn over time
figuring out when one problem is actually two separate problems
Oh I think I have that backwards with Z hold on. Regardless of that though it refuses to move on Y. :C
Apologies that last line should have been the following I believe
crosshair.transform.position = new Vector3(worldPos.X, worldPos.y, distanceFromCamera);
Something like this:
Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
crosshair.transform.position = new Vector3(worldPos.x, worldPos.y, 0);
That is not correct. distanceFromCamera is a distance...from the camera
it's not the actual Z coordinate the crosshair should wind up at
especially not if the camera isn't pointing in exactly the +Z direction
Is this a 2D game or a 3D game?
Ok then I think my brain is just being jelly at this point and I am just not thinking correctly. Its a 3D game with the goal of putting a 2D crosshair on screen.
Might have to come back to this after some sleep cause I think I am not inherintely understanding the fucntions I am working with.
Okay, then just directly assign the result of ScreenToWorldPoint into the position of the crosshair
That will place it at a certain position on your screen, exactly distanceFromCamera meters away from the camera
You dont want to do it like this usually in 3d games you want to shoot a ray from a shooting pos and get that world pos in screen pos and show a crosshair there.
that would be correct if you wanted to stick the crosshair onto the object you're looking at
This would not work in a 3D game, mind you -- https://unity.huh.how/screentoworldpoint
and in a 2D game, it would place the object too close to the camera
Okay let me try this and get back to u, thank you!
Ideally, a crosshair shouldn't really...have a distance from the camera; it should just be drawn directly onto your screen (e.g. by an overlay UI)
Ok that was the other option but any guide I found for doing it via UI was super outdated and had missing/moved tools being used.
So I just didn’t know how to proceed.
A very basic crosshair would be a Canvas with a single child object
which would have an Image and be anchored to the center
You can write a custom shader to create interesting dynamic crosshairs (:
or just stick a + in the middle
hello
how to make a platformer game movements?
with Rigidbody 2D and Box Collider 2D
how would i add that delay
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
The junior programmer path will help you.
time.time timer, coroutine or invoke a function
i cant understand nothing of tutorial
Did you actually attempt to follow the pathways on Unity Learn?
I click in Start Pathway and open a random site of Unity
i cant understand what i need make to start
do the unity essentials first in the pathways, click start pathway, then get started, all you have to do then is read what it is saying to you and remember what it is saying to you.
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Hmmm, maybe in the future I might be a professional developer?
uhh, sure?
If you actually learn there might be a chance of that happening, but you have to learn, especially the basics of unity
scratch is a "language" made for absolute beginners, unity is the real deal
yeah
Yes, I'm working hard to surpass the progress I made in Scratch so I can get back to becoming a dev.
GUI.Label(centerRect, "+")
I remember doing that when prototyping years ago
hi y'all :) i've been working on a project for a while now and i think its finally time i change my pickup system, yet the thing i want i cant seem to figure out and cant seem to find online.
I'm looking for the bare minimum, when player looks at object and presses keybind, reutnr Debug.Log("HI!!");
Anyone know how to do this?
use a raycast whenever the desired button is pressed to find whatever object you are looking at and find if it is the object you want, if it is log "Hi"
trying to patch together like 8 small tutorials i found i came u p with this
it doesent have any errors, yet does absolutely nothing when i test it
did i do something wrong?
did you put a debug.log in it to see if the raycast is hitting anything?
yeah in the other script
no, i didnt get anything back which i thought was weird
put another one below the raycast method to see if it is hitting anything
Debug.Log("raycast hit" + hitInfo.collider.gameobject);
still nothing sadly
Are you sure you have the script on the desired object?
show me the new script with the new debug.log in the !code format
📃 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.
yes, and uh
using System.Collections;
using System.Collections.Generic;
interface IInteractable
{
public void Interact();
}
public class Interactor : MonoBehaviour
{
public Transform InteractorSource;
public float InteractRange;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
{
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
interactObj.Interact();
Debug.Log("raycast hit");
}
}
}
}
}```
I mean't place the Debug.Log("raycast hit"); below the raycast method which would be
if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
{
Debug.Log("raycast hit");
//etc
}
ohh
so like t his?
if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange))
{
Debug.Log("raycast hit");
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj)) {
interactObj.Interact();
}
}```
yes
you might also want to use the LayerMask parameter in the raycast method to shorten the search of objects that can be hit
how would i do that?
also- the debug didnt work again
Like this:
public class Interactor : MonoBehaviour
{
[SerializeField] private Transform InteractorSource;
[SerializeField] private float InteractRange = 5f;
[SerializeField] LayerMask _mask;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if (Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask))
{
Debug.Log("raycast hit");
}
}
}
}
what does seralizefield do? (also, seralizefield errored when i tried to use it lol)
you should probably configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
SerializeField so with that you are able to see variables in editor but not make them public
ohhhh
nevermind, if it did error and does autocomplete you are fine
these are what my errors look like if thats what y ou mean
SerializeField and SerializeFieldAttribute isnt same
do you see red squiggly lines in your IDE?
I didn't put serializefieldattribute
IDE? you mean my code or- (sorry im still a beginner lmao)
The program you are using to code Like VisualStudio or VisualCode
Integrated Development Environment, AKA VS or VSC
you should probably configure your IDE using the bot above
it will make things a lot easier
okayyy
update-
i went to those little links you sent and followed it, but everything says thers no update available
You are using VS Code right here is a video tutorial for you to see how to configure it https://www.youtube.com/watch?v=-AgcVsS-rtQ
In this video you will learn how to configure Visual Studio Code for Unity development. You'll learn how to get many things working including syntax highlighting, debugger, auto formatting, and snippets.
is there a way to select 2 rigidbodies and quickly define if they the same object based on joints
so apparently-
my extensions are bugged is what it looks like? i uninstalled and reinstalled them, but im s till getting a ".NET SDK" error, and have no idea what that means
done, but now something else is erroring w hich i think is the squiggly lines you were talking about?
select both objects they are on (you can cuse cntrl click) then on the right of the screen you should see rigidbody properties, and if its the same it should show the same object, and if they dont have something in common it'll come u p with ---
that or im stupid and im thinking of s omething else
i mean in script
Hi, is it the correct method to avoid the click event being responded to by both the red child and the purple root at the same time by using the method shown in the red box in the figure?
oh in that case no?
although, you can see if specific properties are the same i think using gameObject.getComponent<script>.property
although in your case it'd be rigidbody
then you can see if (line) = (line)
That is not the squiggly lines I was talking about, I have not seen that error from VSC before but from a glance it looks like you need git but I don't think it is required for VSC configuration
you could restart to see if it goes away, also you should continue configuring your IDE if you have not already
already tried restarting
i think i have configured it
well do you see intellisense (i.e autocomplete) and do you have red squiggly lines and errors in the VSC console?
noo...
Then it is not configured
if you followed all of the steps you can regenerate your project files in the external tools menu of preferences in unity
can i do the raytracing thing without configuring it?
id prefer to do configuration another day honestly
sure you could continue tinkering with the raycast but it would be a lot easier if you did configure it
I would suggest !learning unity a bit more to understand these basic concepts
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
alrighty, but about raycast-
how do i proceed from where i am?
First check if you are hitting anything with raycast.
i did and it still didnt do much of anything
there was no errors, and when i w ent up to the object and pressed E it still didn't work
show me your inspector with the object in frame
like this?
uh- the video i wa tched said it shouldn't go on the object, rather a different script that checks in the interactor script sot hat i could easily apply it to anything
public class TestInteract : MonoBehaviour
{
public void Interact()
{
Debug.Log("hi");
}
}
you must have that script attached to something, I'm not familiar with interfaces so I couldn't go in depth into them.
you should use this link to learn unity, It's pretty late for me so I'm going to go
#💻┃code-beginner message
Where are you calling Interact?
like, where am i stating it?
in a different script
using System.Collections;
using System.Collections.Generic;
interface IInteractable
{
public void Interact();
}
public class Interactor : MonoBehaviour
{
public Transform InteractorSource;
public float InteractRange;
LayerMask _mask;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if(Physics.Raycast(r, out RaycastHit hitInfo, InteractRange, _mask))
{
Debug.Log("raycast hit");
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable interactObj))
{
interactObj.Interact();
}
}
}
}
}```
@elfin isle The other script needs to implement the IInteractable interface for it to work. Go through the tutorial again and pay more attention.
the shorter script needs it?
(i remember putting it there im gonna be honest i dont know why its not)
but i just tried it again with it and it still doesent work
Yes, it needs to implement the interface.
Tried what?
I don't see your monitor from here.
i ran the code and added the IInteractable interface to it
Share the updated code.
public class TestInteract : MonoBehaviour, IInteractable
{
public void Interact()
{
Debug.Log("hi");
}
}```
So the log is still not printing?
yeah
Does the raycast hit print in the console?
And are there any errors?
I added vfx assets in a random moment I got this. How long can it be? Can I avoid it?
More than sure it will discard some changes, on top of it if I just close Unity, these vfx assets will be pink
yall think it would be practical and possible to do some sort of partial ragdoll physics for character flinch
like where the physics would determine the direction you flinch
hello everyone, how do i optimize the following code? https://paste.ofcode.org/34ktUYRXvczghMpKFUghwdt
its for optimizing particlesystems but i think im missing something because with a lot of particlesystems its lagging about as much as the particle systems are
Maybe. Whether it's worth the effort and performance costs is up to you.
Mm... I feel like particle systems already have frustum culling implemented.
ill test it out
using UnityEngine;
public class TUT : MonoBehaviour
{
public AudioClip stop;
void OnCollisionEnter ()
{
AudioSource audio = GetComponent<AudioSource>();
audio.clip = stop;
audio.Play ();
}
} ```
dosent play on collision.
are there any other issues other than that?
is there a collider
yups
Not really. It's just that if what I said is true, you're basically doing what unity would do already(potentially in a less efficient way).
If you're doing optimizations, you should do it based on profiling data. Not just randomly.
Add a debug log. Also, I don't remember if a prameterless collision message is a thing...🤔
dosent print on collision
Does the other colliding object have a rigidbody+collider?
yes
i just duplicated something that does collide and then applied this script to the object and now it dosent collide for some reason
You'd need to share some more details then.
have you put a break point in OnCollisionEnter() to see if it's being called? or a Debug.Log()?
i have added a log, dosent call
have you tried a new scene with the bare minimum needed?
ok ill try that rq
anyone able to help with figuring out how to get my current movement script to work with Sebastian Lagues Spherical Gravity implementation?
https://hatebin.com/bvpdpsbkkd
https://www.youtube.com/watch?v=TicipSVT-T8&t=192s
Hi there, welcome to this tutorial on creating a simple first person controller that will function on spherical planets.
Updated source code for Unity5: https://github.com/SebLague/Spherical-Gravity
Original source code: http://pastebin.com/YBbFGZzD
Download the world model package by @danielsound here: https://www.dropbox.com/s/ul53h1g3nb5b9e...
bruh nothing works
i tried to just make my moveDirection be
moveDirection = transform.forward * verticalInput + transform.right * horizontal input;
to make it work in the local space but it comepletely ignores my camera so sometimes my W key wont actually move me the way im currently looking in the local space
I also have a bit of a problem with how jumping works, it doesn't seem to detect if my player is grounded or not once it reaches a certain point on the side of the planet
might get better response from this being in code-advanced. this isn't trivial.
ok
so ... new scene, you've added a cube with rigidbody and TUT script, added a plane underneath the cube. press play, cube falls and hits plane but OnCollisionEnter() isn't called?
void OnCollisionEnter(Collision collision)
Does unity call component update functions on gameobjects in dontdestroyonload before objects in the main active scene?
I want to make sure a certain singleton’s update is executing before a different monobehaviour’s that depends on it being set
No. There's no guarantee what order they would be called in. Better not rely on it.
There is no guaranteed ordering
Or, should I just do it in Update and LateUpdate?
I just thought of that and it makes so much more sense
Or use an event
If you have to do that, there's probably an issue in your system design
Rendering is basically the last thing that happens in a given frame
I’m porting a game made in monogame to unity and its all hardcoded in 1 long update function and draw function
So I want the order of stuff to mirror it as closely as possible - at least the things that depend on each other
This certain timer is supposed to increment right at the start of the update before its used anywhere further
But Update/LateUpdate solution will work just fine for this
Is this is a bad reasoning for doing that btw?
.-.
Problem is, I guess that approach will only get me so far. It works for this particular case, but There is no infinite amount of updates in between Update and LateUpdate…
Oh the event approach, so like the timer updating thing would invoke one
and the listening components would work with it when they receive said event
can anyone explain to me how momentum works?
Right praetor? Thank you
so basically i got this normal fps movement script except the only relevant part is the hooking mechanism. basically when you hold e you cast a ray from the player's camera orientation and if the ray detects an object tagged "enemy" you get pulled towards the object. it has its own ease-in and ease-out but that doesnt matter. what i want to do is when i release i dont want to stop in mid-air and instead i wanna keep going in the same direction i was going with the momentum i was going with. can anyone help me out?
put the enemy in a variable and the movement force in another variable. each frame, move the player towards the enemy by the movement force. when E is released, decrease the movement force slowly until it reaches zero.
if the movement direction doesn't change (i.e. is set when you press E initially and you don't want to follow the enemy) then you can use a Vector for the movment (as you don't need to track the enemy)
idk if this is the channel where i should ask this but im really new to this stuff im trying to get just a png of a gun in front of the camera for an fps no 3d model or anything, how would i do this?
Place a quad with the texture on it in front of the camera and make sure it's properly in front of the camera
Even easier is to have a gameobject that uses the same coordinates as the camera (don't put it inside the camera because it will just create a lazy dependency on it) and to then put that quad in there. It saves the effort of having to figure out the coordinates
Is it good idea to disable unity editor reloading domain on play
Is there a reason why you ask this?
I want to know i seen it on Youtube
Do you know what domain reload is? Do you have an issue with domain reloading?
If you answer "no" to these, then just leave it as it is
Unless you actually have an issue with it or want to speed up switching between edit and play mode, you can disable it. Note it exists for a reason, so you should be very aware that disabling it will have considerable effects on development
Also, if you are following a Youtube video which suggests you disable it, but doesn't explain why, I think you should stop watching that video because that person definitely doesn't know what they are talking about
hello guys I'm new to unity and I want to learn it.
Which tutorial channel should I watch?
(Bu cümle türkler için) Unity'de yeniyim hangi tutorial kanalını önerirsiniz? En/Tr farketmez.
Learn to develop games using the Unity game engine in this complete course for beginners. This course will get you up and running with Unity. Free game assets included!
✏️ Course developed by Fahir from Awesome Tuts. Check out his channel: https://www.youtube.com/channel/UC5c-DuzPdH9iaWYdI0v0uzw
⭐️ Resources ⭐️
(To download assets you may have...
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thank you
does anyone know how to add trimping(like tf2) to a non rigidbody character controller?
this is a side effect of the way source2 is made, all players have their own rigidbody. collisions are resolved by changing the player's velocity. if you have forward velocity, and you hit an angled ramp, your velocity is changed to be facing upwards instead.
to do this in a non rigidbody character controller you'll need to keep track of velocity. when the player dashes, add a forward velocity to your character. when the player hits a ramp, calculate the angle at which the player hit the ramp, and change the direction of the player's velocity from there.
even if you do use unity's rigidbody you may not get the same experience as source2's physics. youll want to study source2's physics more in depth
so i need to calculate each angle of every ramp the player is on?
when the player collides, yes
computers are fast enough nowadays youll be fine
ok ty
when we talk about "expensive" it matters most when youre doing it for hundreds of thousuands of players, but in your game you probably just have your main character doing it
in other words you can get away with it
oh ok
good luck
ty
guys what tutorial would u recommend in making a 2d top down rpg game, im pretty new to unity
hi im trying to make ui for my game, i made a canvas and added a text mesh pro as a child, and this works but in the editor the canvas looks way bigger than the game, id prefer it to be the same size so that i dont have to keep zooming in and out, really not sure what i would google so im asking here 🙏
I suppose you can scale the canvas down, but reality is you're stuck with your 2D and 3D elements trying to co-exist in the same space (bit of a Unity quirk from its unified 2d and 3d support) so it will always look a bit strange as long as you're dealing with screen space and world space elements in the same scene view.
My tip would be to right click the Scene tab and go to Add Tab -> Scene and have a separate Scene tab that is zoomed and aligned specifically for your UI, or alternatively create a prefab out of your UI hierarchy that you can drop in and out of to make changes.
ahh alright, thank u!
This is a code channel and you're asking a non-code question. Post in #📲┃ui-ux for UI questions!
I suppose you can scale the canvas down
You can't scale a screenspace - overlay canvas
oops mb, new to the server
read the channel names, the topics and #📖┃code-of-conduct 😄
Now where is the Death Loop that makes my Unity Editor crash once i collide with an object using this script?
private void OnCollisionStay(Collision collision)
{
if (collision.collider.tag == "Player")
{
if (flagPercentMeter < flagPercentMeterMax)
{
flagPercentMeter += 0.1f;
}
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.collider.tag == "Player")
{
while (flagPercentMeter != 0)
{
flagPercentMeter -= 0.1f;
}
}
}
The while loop, the only loop in this code.
It's impossible for some random float number to land exactly on 0. You want to check if it's less than, in order to stop.
Isnt OnCollisionStay considered a "Loop"? i assumed since i believe it is called every frame?
just for my personal udnerstanding
I guess that's one way to look at it. But it's per frame. The reason you're freezing is because you're stuck in an infinite loop on a single frame.
Thank you!
im using the abstract class wrong right
should it be a normal class and then just System.Serializable
An abstract class cannot be instantiated -- it isn't a complete definition
im still trying to wrap my head around them
as i discovered them the other day
its like a base class for example for like a weapon
which would share all things each weapon would share right?
so like Shoot() method
ammo and magazineSize
or am i thinking wrong
and i'd then make another script like sniper, and make it inherit from the Weapon abstract class
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I wouldn't even use multiple classes for this
A sniper rifle is not conceptually different enough from a pistol to be worth the distinction
They'd both be a Firearm with different configurations
Most of my abstract classes are for things like filters and scorers
true
[Serializable]
public abstract class Scorer : IPolymorphic
{
public abstract float GetRawScore();
}
[Serializable]
public class ConstantScorer : Scorer
{
[SerializeField] private float value;
public override float GetRawScore()
{
return value;
}
}
e.g.
However, this is the rough idea, yes
In that case, a Firearm would be too ill-defined to exist on its own, and you'd have to derive from it and implement its abstract members to get a concrete class
Firearm whatever = new Pistol();
whatever = new Rifle();
whatever = new Firearm(); // invalid; you can't construct a Firearm
I just made a shooting script and weapons exists as scriptableobjects configs
wonder if it's better or worse than having shooting logic on weapons
so, how do I properly create an empty gameobject via code?
What does this question have to do with the first two sentences?
totally nothing
And generally it would be better to instantiate a prefab than create an empty GameObject
but creating an empty GameObject is as simple as new GameObject()
is there a way to use instantiate for that?
I don't understand the question. You can use instantiate instead of that.
you would instantiate a prefab, as mentioned
Instantiate(myPrefab)```
that answers what I need, however, I wonder if there is an API to conveniently spawn a gameobject and set it's partent, rotation, and positon
but like, completely empty one
I can set each separately in a line of code
You could just use Instantiate
with a prefab
the prefab can be empty if you really want.
but it seems weird for it to be
creating an empty preferab feels really wierd
Why does it need to be empty
A GameObject without any components is useless, and presumably you plan to do something with it
I use makeshift origin shift system and I have something which lerps between 2 positions, if I just make those positions simple vector3 on world shift it would broke, so I create empty points so they are in the list of things getting shifted
ok i mean - you have two options:
- empty prefab
- make a helper function that does all that in one line.
fair enough
speaking of origin shift - is there anything better than just manually teleporting a list of transforms?
and rigidbodies instead of transforms if it's a rigidbody 🤷♂️
I have a component that makes a text pulse in and out opacity. The thing is, I want every text object that has this component to be completely synchronized. How would I go about doing that?
Change the script to use some kind of global timer instead of a local one
or make one script that pulses them all in a loop instead of each handling its own
There’s no way to handle it with just 1 behaviour is there
Change the script to use some kind of global timer instead of a local one
I’d need some sort of MouseTextSystem singleton in dontdestroyonload and a MouseTextPulse or smtn
somthing like float lerpValue = Mathf.PingPong(Time.time, 1)
Not necessarily... just use a global timer
yeah but then it gets incremented faster/extra
if more instances exist
not necessarily
that comes down to how you write your code
add each new text to a list. loop through the list and have each one use the same global value(s) . . .
sure, that's one option.
Or use Time.timeAsDouble
The problem is that i need the opacity variable to be changing even if no object with a MouseTextPulse is active
Then you have two options:
- some central handler
- Time.time(asDouble)
That’s what I figured
I would have to right some strange logic with time.timeasdouble
yeah, that's what something like that would work
Mathf.PingPong(Time.time, 1)
Time.timeAsDouble is better I guess
Like mathf.pingpong
What's "strange" about it?
Those methods are unfamiliar to me so I avoid them usualy
it's just a little math
What happens when its a case where its not a linear triangle wave of up and down opacity?
you can write whatever logic you want
Are there any cases where Time.timeasdouble would fail me?
To get a repeating animation
insert whatever animationcurve you need
Imagine there were 3 states instead
You can even use an ANimationCurve, yeah
Fade in slowly, fade out faster and etc.
You can do anything you want with the right code
Oh the animation curve lets me get a value for a given t?
yes
Never used an animationcurve before
That sounds like exactly what I’d need
thank you guys
AnimationCurve is the simplest/most configurable option
So then if it gets called more than once on the frame it’ll be deterministic (Using time.timeasdouble)
or the same i mean
For every object
and I can still cache it the first time its calculated, for the rest of the frame maybe? or is that a pointless overcomplication?
that would only makes sense if you have something iterating through all objects, I think
yeah, like, time doesn't change within one frame
the calculation would be redundant to do say 100 times in the same update
it would be redundat but calling an update for each text instance is also redundant
I want to do it from one single behaviour
this case yeah do it once
So i was thinking to make a static field
most likely not worth it
The thing is I have code like lastTime and compare it to currentTime but I dont know how precise this is
probably not
It would be precise in this case but you could also just do Time.frameCount comparisons which would feel nicer
Why “in this case” would it be good? Also, thanks, Time.frameCount sounds like what I need.
because Time.timeXXX things only update once per frame
I mean, if it cycles through all objects, you save whole... okay, around nothing from PingPong but it still feels good
even though they're floating point numbers they will bitwise the same value throughout the whole frame
I wouldn't really even use PingPong
yeah, but I meant the act of comparing a stored lastTime to a new time.timeasdouble. If the fps is too high, wont the value have barely changed, and inaccuracy exist in comparison?
just something like
public AnimationCurve curve;
void Update() {
float time = Time.timeAsDouble;
time %= 1;
float opacity = curve.Evaluate((float)time);
}```
Or is double very accurate
right, if it's one instance doing it for everything, separate timer makes more sense
there would be no change in value because we're checking during the same frame just to see if the frame is the same
but again Time.frameCount "feels" nicer for this anyway
so we should use that
I said that because floats suck but idk about double
I meant when it changes the next frame
Sorry if that wasnt clear
I understand that, what you are saying
I don't get it why would you need that
I need to call the method that caches the result of the calculated color only once per frame… so there is a comparison of (lastTime != time.timeasdouble)…. I guess what I’m asking is if when time.timeasdouble increases smally by the next frame, is there low accuracy?
Sorry, this stems from a bad understanding about how doubles work. Am I confusing this for floating point inaccuracy?
So I have my SwipeDetection class that I put on my Managers Empty GameObject (as tutorial suggested), now I wonder how I can emit event from that class and based on that event do some action in my PlayerController class so that I can move my player around.
because they would/could do something like this:
static float timer;
static int lastTimeUpdated;
void Update() {
if (Time.frameCount != lastTimeUpdated) {
timer += Time.deltaTIme;
timer %= 1;
}
float alpha = myCurve.Evaluate(timer);
}```
Now I don’t really know the context and I’ve only read up a bit but if this is what you want why would you not just use an animation
Yes that is what I would use
What you're confusing is that Time.time and Time.timeAsDouble don't update during a frame
they change once between frames, and not again at all during a frame
Bruh no i get that
By the next frame when it changes
Not an animation curve like an actual animation
Is there a reason ur scripting this
time.timeasdouble increases smally by the next frame, is there low accuracy?
The==operator for double and float check for exact accuracy
lasttime and time.timeasdouble arent the same anymore (the latter has increased)
they need to literally be the same bit pattern in memory
so the branch should execute once per frame right
ohhh
thanks
that is what I was asking
but yeah I'd still use Time.frameCount if you're doing that
doubles are more accurate. not much of a precision error compared to floats. is there any reason you haven't tested it yet? doing so will quickly see if there is an issue . . .
oh that's... nice but it feels odd
is this how people making sure calculation works just once per frame?
is this a common practice?
The main thing with Time.frameCount vs Time.time is that frameCount will continue to increment when Time.timeScale is 0
I wouldn't say it's common. It's more of a hack.
also I lost it on
timer %= 1;
what would that do
It's usually more flexible/extensible to use a singleton
% is the modulus operator (or to be technical, it's the remainder operator)
it would just keep the value in the range 0-1
1.25 would become 0.25
it's to make it loop
so basically pingpong(value, 1)?
ah okay
I would just use events for this if you’re for some reason set on scripting it and not using an animation
nevermind I just googled the thing and got a nice understanding
Just have some event that passes in the time when the frame changes and just listen to that no need for all this duplicate redundant code being run in update every frame
yeah that's what he said about having a singleton being more useful
You would need a single driver to trigger the event yeah
And a single place to subscribe to the event
Well yeah but I wouldn’t hook the text scripts directly to the singleton because it really isn’t any harder takes like 2 minutes extra and just completely decouples them
I suppose though but I feel like its just extra to have a MouseTextSystem behaviour in dontdestroyonload and also a MouseTextPulse
Maybe ill use that instead
I thoight if I could contain the whole behavipur on one script itd be nice
I’ve said this before but why are you not using animations for this
Well using an animator seems overkill for this no? And also introduces other challenges with syncing them.
agh the issue with Time.time(asdouble) is that it dont get capped like time.deltatime does by default
For long pauses between frames
or times
I feel like eventually one disavows themselves of such notions, but I guess it's personal preference.
I mean I can’t really agree
Animation system isn’t exactly complicated
Far easier to tweak the animations if you want it
And have multiple ones you just add another animation
Instead of having to script
You have to:
- Attach an animator
- Make an animation clip
- Make a state machine
- Figure out how to sync them all (which needs more code, probably another script)
Didn’t they say they wanted different speed animations and stuff like one that’s slow one that’s fast or whatever
AnimationCurve and a little code just seems easier to me until they actually start needing all the extra animator features
Come on this takes 45 seconds and ‘syncing’ the animations is easier than syncing a bunch of stuff with time.time and a bunch of maths
Disagree
I mean writing this code took me about 20 seconds
there's no maths
the curve handles the maths
I’d sooner use animations now than have to remake everything when I end up needing that extra functionality
The other approach is having a singleton MouseTextSystem singleton that increment a field in Update, and a separate MouseTextPulse behaviour thats as simple as _text.color = MouseTextSystem.Instance.color in LateUpdate
Hey i have this public SavesManager but when i try to drag and drop the saves manager script it doesnt let me
I think you are vastly overstating the time it takes to drag and drop an animation controller onto some text
Anyway this subject has outlived my attention span
meanwhile you vastly overstating how hard it is to do that without animations
You can't drag scripts into those slots
those slots are for GameObjects that have the script attached
I’m not
It’s easy
And you are vastly overstating the 3 lines of code.
oooooh yeah, thanks
Probably depends on your familiarity level
I guess its not the end of the world to have 2 different behaviours for this
Im just not sure about polluting dontdestroyonload with such a basic singleton
idk if it would have any downsides
Or should I not care
I mean
And here we see an issue that would be fixed by not using it with a singleton and scripts
I was wondering if anyone could help me. I'm on a fresh install of unity, this is my first time using it. All I'm trying to do is get my character to move left and right, nothing special.
Except my character constantly moves left.
I've checked for inputs in the input debugger, nothing. I disabled my movement script to see if it's a physics thing, still goes left.
It seems that for whatever reason, either there is some constant left input from somewhere I can't see, or my linearVelocity is getting multiplied by -1. I've been at this for hours, google is no help.
One message removed from a suspended account.
Cross scene management is a lot easier without singletons
what's your movement code?
how are singletons and scripts worse than having an animator for each animated text
Can you send the character movement script
How is that, wouldnt it be easier cause they persist?
I need it to be active on every scene anyways
why
Hi, please share the !code thus far so that debugging tips can be given
📃 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.
just a check on awake
If it’s per scene I would just create a single object with teh behaviour attached to it
Not use a singleton
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float runSpeed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
body.linearVelocity = new Vector2(Input.GetAxisRaw("Horizontal"), body.linearVelocityY);
}
}
Because you can use like… an so event channel in project files instead of an object in a scene that needs to be constantly loaded in a ‘shared’ scene
I gonna be honest I hate animators because they tank performance but I never really profiled them, instead I just use as few of them as possible
One message removed from a suspended account.
oh you mean having several scenes at the same time
Try debugging the values. Specifically try debugging the result of Input.GetAxisRaw("Horizontal") and body.linearVelocityY. My guess is one is a constant positive value. https://unity.huh.how/debugging/logging/how-to
I never encountered a need for that soo I can't tell about that
Yes
have you looked into character controller
If you want to have a singleton accessible throughout the entire game
And you also need to scene switch
You probably want to have the singleton on a separate shared scene
One message removed from a suspended account.
You probably have a gamepad plugged into your pc you forgot about
I just download a new scene and a new scene singletone is the singletone, the old one is discarded
That depends on the singletone tho, some are on Don'tDestroyOnLoad thingie
I suggest you !learn the fundamentals of Unity. At some point you will learn of rigid bodies and the build in character controller
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
One message removed from a suspended account.
You are not meant to modify Rigidbody.linearVelocity
One message removed from a suspended account.
Don't skip learning Unity just because you want to create something. Learn from the video's provided and you will find out how to make a character controller as you go
no that's fine
One message removed from a suspended account.
thats dontdestroyonload?
my singleton implementation already have this
it put it there
Citation required
Yes I’m explaining to the other guy
ohhnvm
void Update()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
body.velocity = new Vector2(horizontalInput * runSpeed, body.velocity.y);
}```
Try this
One message removed from a suspended account.
Let's aim for 24 hours a day
most cases being physics. player movement doesn't have to be physics, you can just control it directly if you don't want any fancy acceleration/skid
Then you should use a kinematic rb instead of modifying the velocity!
no, a player still should be subject to gravity and collision
nope. Two charging cables and a webcam.
it took me around 2 months to have a grasp on doing C#
to understand whats going on in code I search 95% of the time
btw folks is it a good or bad time?
You understand that modifying linearVelocity is letting the physics engine handle the movement right?
Well - Debug.Log to see if Input.GetAxisRaw is returning -1
physics out, yes, but direct in rather than physics in
there's nothing wrong with this
Then I would definitely begin by logging the values I mentioned
it could be made simpler though with:
body.linearVelocityX = Input.GetAxisRaw("Horizontal");
Well ok we’ll ignore that there is a different way to do it that results in the exact same outcome while not doing something the documentation says not to do and will cause issues
The documentation never says not to modify the velocity
alright arch; if you aren't meant to modify the velocity directly, how would you suggest direct control without acceleration or skidding
"In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour"
It is returning -1
not an industrial simulation
Then you indeed have some input device stuck
unpluig all devices
disable bluetooth
make sure your keyboard doesn't have a cat resting on it
I have never heard of a case where an input device can be stuck like that, interesting
Usually I've gotten my keyboard wedged under something on my desk which causes this kind of thing
Rb.move 👍
that ignores collisions
(At least in 3d)
Modifying velocity is functionally equivalent to AddForce
AddForce does one thing and one thing only, it modifies the velocity
it's just a matter of additive vs overwriting
you can achieve the same thing with either
Cat unplugged, bluetooth stroked, usb devices disabled
so you'd have to manually compute the target position while taking into account vertical forces yourself
They only have that warning because most people are not thinking carefully about what they set the velocity to
Still goes left
restart PC
Ok
have you tried pressing a/left to reset the button
Literally first thing I tried
rq if you haven't restarted yet; try a keyboard test site
The term key rollover refers to the number of keys that can be simultaneously registered by a keyboard. The following online key rollover test makes it easy for you to verify specifications from manufacturers. You can try out various key combinations and test how many keys your keyboard can handle at once.
Odly enough I recently run into a problem where Unity would think that certain webcams were joysticks
Maybe it’s that
Right ^ which is why I recommended unplugging all devices
it's got a wire and sometimes a switch, close enough
weird
FBI agent using his spyware and having a laugh
ghosts
Oh I am not the only in possession of this esoteric knowledge I see
Yeah are you under federal investigation?
Not that I know of...
If you knew they wouldn't be doing their jobs right
I work for a rather large tech company though so maybe...
Right I bet the reboot yeeted the webcam driver
If correct physics is what you want then setting rb.velocity every frame isn’t exactly gonna be grand
F*** me sideways with a chainsaw...
It was my HEADSET CHARGER
I suppose you could set once on key down with no drag
what even
how
But that has other issues
Again, this is a video game. We very rarely want "correct physics"
we want responsive gameplay
That isn’t exactly hard to do
Ok we can add ….”headset chargers” to the list then
Good to know good to know
Specifically Jabro
That’s not really what I mean but ok nvm
ok then what do you mean
it isn't, but just setting a velocity is a lot easier
and especially for beginners, there's less to get wrong
So I’m not saying physics on the game has to be realistic, but setting rb vel every frame can result in stuttering and stuff when you hit walls or get hit by objects
That’s what I mean by ‘unrealistic’
in my experience not at all
collisions are checked before stepping velocity
like the docs for MovePosition mention, lol.
It has been horrible for 2D in my experience I can say that much
You've been doing something wrong
make sure you're doing it in FixedUpdate and not Update 🙃
though actually doing it in update shouldn't have any issue either
With interpolation on (not none, not extrapolate)
since it's an overwrite and not a modify
Either way if super responsive feel good movement is your aim and you don’t care about external objects acting on your players rb I’d sooner use a kinematic rb any day
why wiuldn't you care about external forces
like mentioned before, gravity
and yknow.. collisions
why remake it all when it's built-in
You are directly setting rb.velocity every frame
If that is how you decide to go about things I would heavily assume you don’t care about like… having objects hit you and they move the players rb
and you don’t care about external objects acting on your players rb
Seems very unlikely. Especially not caring about colliding with waqlls
but you normally care about the player not going through walls
aight ill test this when i get home
Think about Mario
Mario is the gold standard of platformer
he does not react physically to objects hitting him (thinking 2D marios here)
he dies
Completely wrong, suddenly not fixed again WTF?!
thwomp damage boosting 
Call the exorcist
and do another sweep for USB or bluetooth devices
I tried. Mike Oldfield showed up instead.
Ffs like I said I am not saying this is the way everyone has to go in their games
But if you DO care, directly setting rb.velocity every frame is not it
Sure, and I'm just saying you are acting as if directly modifying horizontal velocity is a very unusual or dangerous thing to do - it isn't.
obviously, your movement code depends as always on your game's specific requirements
I’m not trying to say it’s the end of the world, but I don’t personally see any usecase outside of ‘it’s quick and easy’ for a prototype
Just direct setting velocity neither works well with external physics objects, nor does it feel especially good or fluid
There are a lot of games for which physical accuracy is not a priority.
The "feel" of it depends heavily on what you set the velocity to though
Is there no way to find the source of input without trial and error?
there may be a misconception that we have to directly set the velocity to an analog of the current input value or that our movement code must be two lines long
You can try the new input system's input debugger
And how does that work?
Yes, what I’m saying is if that’s the case, and you have complex movement calcs to create great feeling movement, I’d sooner just use kinematic and handle collisions urself; it’s not really that hard to do so
I have these 4 inputs. Currently, none of them are showing anything happening
Interestingly, there only seems to be a -1 input when I have the game window selected
Otherwise it shows 0
Well that's... sort of expected as the game usually doesn't process input unless it has focus
It worked once after that reboot, but hasn't worked again since. I'm so confused
I've unplugged everything
Did you test the keyboard thing
e.g. with this
yes
It says no keys pressed when I press no keys
Went to Edit → Project Settings → Player → Other Settings and changed to new input settings. was previously on both
Now errors
UnityEngine.Internal.InputUnsafeUtility.GetAxis (System.String axisName) (at <c8b1b15e0c1a4cccb2a9ed91e2ed21c8>:0)
UnityEngine.Input.GetAxis (System.String axisName) (at <c8b1b15e0c1a4cccb2a9ed91e2ed21c8>:0)
PlayerMovement.Update () (at Assets/Scripts/playerMovement.cs:21)```
That one is self explanatory
you should/could switch active input handling to Both for now.
I personally have no idea, but you haven't given anything for anyone to help you with. See below !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Well since it works on my Windows and Mac i assume it's just an iOS restriction this is why i didnt show any code
do you think it should be in this channel or advenced?
so why did you put it in a code channel? that doesn't make much sense lol
because idk where to put it haha..
i added the socket class i used, ill move the question there
one must imagine sisyphus happy
im not seeing the issues you mentioned
top of my head, as your code contains very little debuging I would guess at a CORS problem
doesn't iOS have its own version of logcat? Check for errors first etc
Trying to follow good programming practices, what is the best way to reference object A to object B, when object B is created during runtime? Obviously I dont want to use any Find() type methods. Object B is meant to move towards object A
whoops replied wrong message
not gonna argue the latter point since it's subjective, but im not seeing any collision issues at all
I just took a glance at the conversation above, but setting the rigidbodys velocity directly should be fine. 🤷♂️
DI (dependency injection)
I have not had any collision problems with it
so basically my spawner of B objects should have reference to the object A, and pass that reference during initializign the object B?
alright i'll go with that, thanks
but that doesn't sound right for me i think, let me break this down a bit. Right now i have EnemyBase.cs that has reference to EnemyStateController. I also have IState interface, and EnemyMoveState. I have Initialize() method in EnemyBase, and im calling it in the EnemySpawner class
so it'll be kinda big reference chain
welcome to basic dependency injection
passing from EnemySpawner to EnemyBase, then from EnemyBase to EnemyStateController, and then from EnemyStateController to EnemyMoveState
is that ok?
like my EnemyBase doesn't need to know anything about the target of movement
imo not enough info to give a specific solution
that's all i have right now, what more info would you need?
i literally just started and thats all i have
just how its all going to work
#💻┃code-beginner message like here
i could also make singleton from Player but idk if that's okay
so you just need EnemyStateController to have a reference to a scene object?
i don't understand which reference you're trying to pass through
which one is scene object
@wintry quarry
ok
so
bug is back
but
Only when I click off the window and back on.
Then, I have to re-start the unity project to get rid of the bug
oh okay so store it in 1 central script on the enemy if you need it in multiple places, then maybe fire an event so other scripts can also receive it @rare basin
public class EnemyMoveState : IState
{
private EnemyBase _enemy;
public EnemyMoveState(EnemyBase enemy)
{
_enemy = enemy;
}
public void EnterState()
{
PoolManager.Instance.ReleaseToPool(_enemy.GetStartingData().EnemyType, _enemy.gameObject);
}
public void UpdateState()
{
//move towards player
}
public class EnemyStateController : StateController
{
private EnemyBase _enemy;
public void Initialize(EnemyBase enemy)
{
_enemy = enemy;
SetNewState(new EnemyMoveState(_enemy));
}
}
and Init from EnemyStateController is called when enemy is created via EnemySpawner
i can make private Player _player inside EnemyStateController and chain pass the references but im not sure if this is okay? since only the EnemyMoveState needs to know anything about the player
dependency injection is very much a common thing to do, doesn't matter how many scripts you need it pass it to
so can I just store reference to the Player inside EnemyBase
if i need it in EnemyMoveState
if you want something specific from "Player" instead of a Target or something more general
later on yes
i'd need to access player's health
for example
in EnemyAttackState
atleast that is my idea, probably there is better way
why should the enemy need to know about the player's health?
I usually access those at runtime rather than storing a reference, like physics query
exactly that is my concern and thats what i am asking #💻┃code-beginner message
only EnemyMoveState and EnemyAttackState need to know anything about the Player
why not access the component you need ON the attack
like Raycast or Overlap
storing Player is dirty spaget imo
alright but thats different topic, what about the move state thing
i need to specify the position where to move somehow
for the enemy
make a iTarget interface and use Transform or .position/TargetPos
and i dont want the Enemy to know anything about the Player when only EnemyMoveState needs to know the position
that doesn't mean the state itself needs to have access to the player directly. whatever is controlling the state machine can pass relevant info in (like where to move to)
EnemyStateController is controlling the states
i understand that EnemyMoveState just needs a Vector3 position
Vector3 targetPos
done
okay, and i've already provided a resource to you about how to get a reference to the player
but i need to get the player's position somewhere somewhat and thats what im struggling with
where/when do i get the reference to player's position
What's wrong with passing the target player (or its transform) to the state directly
if its a moving state it makes sense to have a target transform / pos
but how can I do it clean way
public class EnemyMoveState : IState
{
private EnemyBase _enemy;
private Vector3 _targetPosition;
public EnemyMoveState(EnemyBase enemy, Vector3 positionToMove)
{
_enemy = enemy;
_targetPosition = positionToMove;
}
public void EnterState()
{
PoolManager.Instance.ReleaseToPool(_enemy.GetStartingData().EnemyType, _enemy.gameObject);
}
public void UpdateState()
{
//move towards _targetPosition
}
public void ExitState(){ }
public void OnEnable(){ }
public void OnDisable(){ }
}
Idk I would probably have a FollowPlayer(Player targetPlayer) method somewhere on the NPC
It would create/set a new EnemyMoveState and pass that player into it
so the goal is simple, i spawn enemy, set new state to EneymMoveState and that's all
public class EnemyStateController : StateController
{
private EnemyBase _enemy;
public void Initialize(EnemyBase enemy, TowerBase tower)
{
_enemy = enemy;
SetNewState(new EnemyMoveState(_enemy));
}
}
i call this Initiailze when spawning the enemy
i just need to pass the Vector3 in SetNewState as 2nd paramter
and that vec3 should be player's position
my question is... how/where to get the player's pos
i can just have reference to the Player in main Enemy class but i was told its not a good idea
Well, is it always "player one" or can they target other NPCs?
since enemy doesnt need to know anything about player
vector3 changes you only have the old value, much better to store a transform
it's always player
Keep the player reference in a singleton or such?
I would just store a Transform or a Target component, incase you want later to change it from the player to something else
except in this case the enemy does need to know about the player's position. so therefore it would make sense to have a reference to it
store it inside main Enemy class?
There's a whole spectrum of valid options here.
i understand that and im trying to figure out what's the good way
i'd need to access other player's components in other states
like EnemyAttackState (i would need PlayerHealth) reference
whatever scripts need a Target/Transform
my EnemyMoveState needs it, but i have to pass it somewhere, and EnemyMoveState is created inside EnemyStateController
again, your enemyattackstate shouldn't need a direct reference to the player health. but again, you're sitting here saying that your states need that info about the player then you go and say that because your enemy doesn't need info about the player it shouldn't have a reference to it.
yeah but also attack state etc.
idk im confused
each scripts should have their own Target component or alike, they are more modular imo
There are many ways to make a state machine
so far that i can use something like IDamageable interface i get it
each script does different thing with Target
There's no single rule for what can know about what
but that's a topic for later, right now i just want to move the enemy towards player 😢
store Transform target and be done with it lol
i still don't see why that means your enemyattackstate needs a direct reference to the player health. surely your attack does some sort of query to see what it hits and can therefore get the relevant damageable component from that query
but WHY should my Enemy have info about the target
when onyl EnemyMoveState needs it
you need to pass it to MoveState how do you want to do it?
question, im saving some info in a json, it apears to get save correctly but when i restart it snt, is this on purpose that unity deletes the info when restarted or is it something wrong with my code
Who provides this information to the EnemyMoveState?
thats my question
What's the best way to store a scene object in a SO? I want a specific image per SO, and displayed when it's active, but i can't drag the object with the image into the SO's image field
somethingis wrong with your code
EnemyStateController
oh yeah, you can't do this by default -- the scene asset type is editor-only
public class EnemyStateController : StateController
{
private EnemyBase _enemy;
public void Initialize(EnemyBase enemy, TowerBase tower)
{
_enemy = enemy;
SetNewState(new EnemyMoveState(_enemy));
}
}
@swift crag
is it only EnemyMoveState or is it other states too? you can't just keep changing the requirements and expect anyone to be able to give you a single straight answer
because here you've said other states require it too: #💻┃code-beginner message
but it's pretty easy to work around
thats on your to figure out how you want to grab the Target
that's my question from the beggining of this convo
Assets can't reference objects from the scene
Wdym with image? An Image component?
but i have several UI elements that exists in the scene, in other so's. stuff like Text, buttons etc
oh, thanks
as you can tell from the replies, the general idea is the same but all the methods differ, there is no specific way to do it lol
y exactly
Oh, you're talking about objects in a scene
I thought you were talking about storing references to a specific scene
is making the player singleton a good idea then
so i can easily reference it whenever i need
Someone will nag about it but it's extremely common
sure but then you have movement scripts with Player.instance imo thats pretty nasty
what movement scripts?
It becomes a problem if you want enemies to be able to attack other stuff
"movementstate" or whatver
or, more generally, do anything to anything other than the player
i guess my entire architecture is fked up
Doesnt seem too fucked up to me
it also becomes a problem if you want to have more than one player (such as for networking or even local)
singleton where a bandaid to bigger issue avoiding a simple proper DI
public class EnemyMoveState : IState
{
private EnemyBase _enemy;
private Vector3 _targetPosition;
public EnemyMoveState(EnemyBase enemy, Vector3 positionToMove)
{
_enemy = enemy;
_targetPosition = positionToMove;
}
}
i'll refactor it like this, and just pass the positionToMove when creating the EnemyMoveState in the state controller
so it's more modular
targetPosition isnt good to store a v3 if target moves / changes position
You might want to follow a player
You might also want to follow another object
So better use a transform reference or maybe an interfacecs interface IPositionTarget { Vector3 GetPosition(); }
That you can wrap the transform into if needed
v3 just store copies unlike reference type
the "more modular" approach would be to have the enemy object keep track of its target and the states just access it from there. that would then allow you to dynamically change the target if that ever becomes necessary. but of course you've been arguing against this option by saying other people told you not to do that
im not arguing at all
just trying to understand, im confused
public struct ITransformPos : IPositionTarget { public Transform transform; public Vector3 GetPosition() => transform.position; }```
That's what the wrapper could look like
literally 20 mins ago
enemy script gets the target then fire OnTargetChanged?.Invoke(target) and other scripts on enemy react to it
#💻┃code-beginner message so that was my answer, but I understand that instaed of Player
it's better to create some kind of ITargetable
I would use something like Target or interface as suggested
I like my NPCs to have a member that is basically a dictionary with values that the states need
And fields/properties for commonly accessed stuff like target
what do you store as keys?
Like the parameters for a shader/material, or the parameters for an animator