#💻┃code-beginner
1 messages · Page 615 of 1
We have no information about the asset you are using or how it is supposed to work. Look through the readme or documentation files on how to set it up properly. Hopefully, there are videos or a walkthrough, but if not, I would contact the author of the asset . . .
this is what was written on the read me
well if the prefabs have scripts on them already you don't have to add anything but the prefabs 🤷♂️
hey guys having problems with my npc not walking on terrain need help pls dm me
#854851968446365696 no ones gonna dm you to help you
ok thanks well can anyone help here then
why would I do more work and go out of my way when you can just post your issue here and I may have answer
i wish i knew what that meant 🥀 ❤️ ✂️ 🪫
#854851968446365696 on how to ask!
@polar acorn i can see my bean body cuz of The Flashlight's light, how can i made it so that it doesnt show my bean in fps mode?
well then you should probably first do the essentials in !learn otherwise its moot to do it here.. You need the basics of Unity editor before you even touch random assets
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Do you need to have a mesh visible at all? If it's first person, just disable the graphics on the player character
but what if i wanna see myself in mirror
or what if its a multiplayer game?
exclude the bean body from the fps camera's visible layers
all i need to know is how to add the animation and then i will (most likely) never ask anything here again
all I need to know is how to do surgery
how can i do that?
real
Worry about those things when you get there
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
ok ty
why is everyone a bit salty here. its not a competition. its called a beginner channel for a reason . no need to flex huh
real
its unrealistic me sitting here doing a walkthrough on how to add animations, this a code channel and regardless you would have no idea where to look if i told you where to go lol. Do the essentials first
lame tbh
rq how do i add a grid pattern to a cube
who's salty? You asked twice about help and never posted a question to the actual problem
An Animator Controller is a Unity asset that controls the logic of an animated GameObject. Within the Animator Controller there are States and Sub-State Machines that are linked together via Transitions. States are the representation of animation clips in the Animator. Transitions direct the flow of an animation from one State to another. In thi...
what specifically do you mean by essentials, can i have a list
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Who is flexing anything right now? You ask a vague question you get vague answers
want to read it again?
How can i simulate dragging a prefab into another object from code.
having problems with my npc not walking on terrain
cant get any more vague than this..
isn't this for 3d
setting the parent after instantiating it doesnt work
"problems" is as vague as it gets
Okay, I will give you an answer with as much detail as possible based off of the information your provided:
"Add code to make it walk on terrain"
ok cool thanks
what have you tried ?
i presume its something to do with the nav mesh perhaps ?
setting the parent
i opened it and first thing i saw was 3d
but that didnt work
Who knows? You haven't even mentioned if you're using nav meshes
Were we just supposed to guess?
if you approach any problem quickly skimming it, then you won't solve much that way
thats what i mean by salty. you are not very beginner friendly
i don't have the time at this very moment to read through the whole thing
then you don't have time to learn the editor to use it ? Then don't lol
You mean setting a reference? You can just set the variable with =.
People are literally trying to get more detail from you, and you have yet to look at the #854851968446365696
People aren't gonna pry information out of you if you cant even read a simple page on how to ask questions lmao
complains gets no help while making the person do all the work of inquiring with 100s of questions .
smort
not today
then do it when you have time
!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/, https://scriptbin.xyz/
📃 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 but i need to set up the animations TODAY
You can't get away trying to drive a car without knowing to even turn the engine on.
real
what you're saying is " I want to somehow know how to do all this without prior knowledge but refuse to look at the material to get me there "
if you "dont have time" then you dont have the time to invest in yourself, and if you wont, why would others?
At some point during child development, a child develops what is known as a "theory of mind". The knowledge that other people do not know information until they are told it, even if that knowledge is true. There's an interesting experiment, if you get two children, one around age two or three, and another around five or six and give them the same scenario: "There is a ball in a toy chest. You take it out of the toy chest and put it under the bed when you're done. If you leave the room, and another child comes in and wants to play with the ball, where will they check for it?"
The young child will say "Under the bed" because, after all, that's where the ball is. The older child will know that the other kid has no way of knowing the ball was moved and will check the toy chest first.
Basically, what I'm saying is, you appear to have skipped that phase of psychological development
We can not see your screen. You have to say the things that are happening or no one here will know what you are doing
i want the solution for this thing only as after that im basically done with my project and i will never touch game development again
we're going in circles here..
If "this thing" is how to add animations, I sent you the tutorial for that
It's also in the learn link you were sent, I just linked straight to the one on animator controllers
but they dont have time digi ! they need this NOW. No time to learn.
"just this one thing, i promise" - everyone who repeatedly came back for help with the most basic stuff because they refused to bother learning the fundamentals of the tools they are using
oh dear
if only discord had a built in counter we could use for the "just need to solve this ONE thing"
this thing isn't how to add animations but thanks anyways
You know, I haven't used that other counter™️ in a while. Maybe I should start a new one
Then what is the problem
writing this script tells me you have no life outside this server. GG x
this bundle pack has an animation code and a character, and im trying to find out how to add that animation onto that character, as it is not written anywhere in the bundle
It took like two minutes to type, if you think that's "no life" then I don't think you're going to get far in game development
dont need to, just having fun my man. dont take it too seriously x
Hm... if only there were a tutorial on how the animator controller works which could tell you how the system functions at a level the asset is likely assuming you understand
You spent more time here insulting and critiquing people than actual put that effort putting details to your question so it would've gotten help instead of roasted.. amazing..who doesn't have a life here..
insulting ? wow
LMAO
have no life outside this server. GG x
anyway no time to waste on these kiddies. blocked and moving on . goodluck with ya
just a response to the initial insult ..
should've spent that time putting effort into your original question instead of crying "salty users"
just an observation
Everyone can stop bickering now, thanks.
it was kinda funny tho be honest
let's not pick that back up
since my game is a 3D platformer and the camera is at a side view I don't want the camera transform orientation I still want to move forward and back with D & A same with the other keys how can I do it?
which way you want forward to be ?
define what forward and back are
and use that
If "D" always means "Right", then just use Vector3.right
No need to involve any transforms in that case
So 2.5D platformer?
@smoky river Don't post off-topic here. Read #📖┃code-of-conduct . And if you are not going to invest time in learning about the thing you are asking don't expect people wasting their time doing it for you.
forward = D back = A away from camera = W and close to camera = S
aight bet
Basically fps movement just the camera at a side view
oh your forward is Vector3.forward
you drew your back and forward arrows pointing the same direction though haha
unless you mean back is the red arrow in Unity
which makes no sense to me
yeah lol thats confusing pointing arrow
Yeah, I interpreted it as "Back is into the screen" which seems like a really wonky control scheme
Yeah in that case back would actually be... left and back and forward would not be opposites
this determines your World directions. If you want to go towards blue, then its Vector3.forward. Etc..
That's what threw me off. Even if that was away from the camera (into the screen) it's still drawn and named incorrectly . . .
Like this? im a bit confused sorry
yes
assuming you want the horizontal input to control "depth"
according to your camera angle
I want to move forward with D not W
(into and out of the screen)
that depends where horizontalInput comes from then
and verticalInput
match up whichever one is A/D with Vector3.forward
I get what you mean the vertical input is the one for A & D so what should I put for W & S?
How should I know - whatever you want it to do
what do you want W and S to do?
W = go back (away from the camera) and S = close to the camera
then you have it correct
assuming what you said about vertical input being A & D is correct
and horizontal input being W and S
er actually
you would do Vector3.left
or -right
if you want W to go into the screen
Have you been testing the code or not? It should be pretty straightforward
just tested it when I press D the player does not go right to move right is W
then you are mistaken about which one vertical and horizontal input are
go check that again
Yeah based on your code from earlier:
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");```
What you said is completely backwards
Following this, horizontal would be multiplied with Vector3.forward, and vertical would be multiplied with Vector3.left
Since forward is your left/right
and left is your up/down
The script is designed to rotate a 3D model with the mouse but have it stay in place, but for some reason it doesn't.
public class MovePrefab : MonoBehaviour
{
private bool isDragging = false;
private float rotationSpeed = 5f;
private Vector3 lastMousePosition;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.gameObject == gameObject)
{
isDragging = true;
lastMousePosition = Input.mousePosition;
}
}
}
if (isDragging)
{
Vector3 deltaMousePosition = Input.mousePosition - lastMousePosition;
float rotationAmount = deltaMousePosition.x * rotationSpeed * Time.deltaTime;
gameObject.transform.Rotate(Vector3.up, -rotationAmount, Space.World);
lastMousePosition = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
isDragging = false;
}
}
}```
It doesn't what: rotate or stay in place?
rotate
I honestly have a problem, So Im trying to make that NPC movement I think mario bros had where the NPCs would turn around and go another direction of a platform if they'd fall the more they walk.
I attempted to use raycast to simulate that movement but I ended up with this issue for some unknown reason.
Gonna also post the code and other stuff in a minute
!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/, https://scriptbin.xyz/
📃 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.
Was genuinely looking what to do for that
Use a paste site. That's the best option . . .
public class EnemyMovement : MonoBehaviour
{
[SerializeField]
Rigidbody2D rb;
[SerializeField]
Animator animator;
[SerializeField]
SpriteRenderer spriteRenderer;
[SerializeField]
float Startspeed;
[SerializeField]
int directionX;
[SerializeField]
LayerMask Hitlayer;
[SerializeField]
float Currentspeed;
void Start()
{
ResetSpeed();
int random = Random.Range(0, 2);
if (random == 0)
{
directionX = 1;
}
else
{
directionX = -1;
}
}
// Update is called once per frame
void Update()
{
Debug.DrawRay(transform.position, new Vector2(directionX * 10, -10), Color.red, 1);
RaycastHit2D hitted = Physics2D.Raycast(transform.position, new Vector2(directionX * 10, -10), 0, Hitlayer);
if (hitted == false)
{
Currentspeed = 0;
int delay = Random.Range(2, 5);
Invoke(nameof(ResetSpeed), delay);
Invoke(nameof(ChangeDirection), delay);
}
animator.SetInteger("MovementX", directionX);
rb.velocity = new Vector2(directionX * Currentspeed * Time.deltaTime, rb.velocity.y);
}
private void ChangeDirection()
{
if (directionX == -1)
{
directionX = 1;
}
else
{
directionX = -1;
}
}
private void ResetSpeed()
{
Currentspeed = Startspeed;
}
}
This is the movement code for enemy
I know the problem is that Raycast isnt counting the ground as something it sees but genuinely why
Might aswell also show what the whole Unity settings of it is, first two pictures are tilemap and grid details for the ground and last two are the enemy's settings
Also Note I havent set the animation yet
why does your raycast have a distance of 0?
new Vector2(directionX * 10, -10)
These 10s mean nothing
raycast uses a direction for one parameter, and then the distance is in the distance parameter
y9ou also didn't show the inspector for the script so it's not clear what you set the layermask to as well.
ohhh
the script inspector is shown tho
Enemy Movement is the script
The layer mask just says mixed so can't see it
oh right
its basically this
alright well - your main issue seems to be the parameters to your raycast being wrong
Hey! can anyone help with unity ar?
I am spawning a prefab on detection of a ref image and the moment it spawn I want to attach the joystick prefab in canvas to it. I'm having a bit difficulty with that.
Also I set the distance to 3 and changed the directions a bit and... this happened
the enemy is just... suddenly funky
Hi, i have this problem, the offset and tilling only moves the silhouette, not the image.
I don't find any solution for this in the internet, has 2 days this problem
Sorry my english
It's also what happened last time should've mentioned which is why I tried setting it to zero
This is the problem
I wholeheartedly dont get it why is the enemy just suddenly breakdancing like oh my gosh
Hey guys im brand new to unity and im having issues with some simple code can anyone help me?
problem is the bird wont jump more than once in this but its picking up my keys. the tutorial is using velocity and i seen thats depercated to now linear velocity.
Code:
using UnityEngine;
public class BirdScript : MonoBehaviour
{
public Rigidbody2D myRigidBody;
public float jumpForce = 10.0f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidBody.linearVelocity = Vector2.up * jumpForce;
}
}
}
video needs to be mp4 to embed
Continued from #💻┃unity-talk message (This is why there's rules against cross-posting!)
Add Debug.Log(myRigidBody.linearVelocity) right after you set it, what do you see in the console as you mash space?
just deleted the old one staying in this one now.
like this should work in theory? idk why it does that problem
Actually, looking at this video, it does seem to be going up. Look at the Y value in the inspector, it keeps increasing.
The camera is falling
it can do that?
If you gave it a rigidbody
Show the inspector of the camera
Either it's falling or it's upside-down
because that bird's Y value is going up
thank you so much for your help! i owe you
Sometimes it's a good idea to put some sort of background element fixed in place so you have something to compare movement against
ill do that now. never touched unity before this so i apperiate the help.
Hello guys! I'm trying to learn how to use Animation Rigging.. I'm following a yt video, and did exactly the same (with a different model), but elbow is not moving.. I'll upload a small video if I can
Is doing a GetComponent on the collider that a raycast from the camera hits every update a bad idea? I know that GetComponents are expensive but I can't think of a better way to get some properties of an object i'm looking at.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RaycastHit-collider.html
The raycast will already give you back the collider.
I know that
After I get the collider and the gameobject of the collider, I am going to do a GetComponent to get a script
its normal
try hundreds
on a slight efficency note, always good idea to have TryGetComponent instead. So you have benefit of null check too
GetComponent should be avoided whenever possible, but sometimes that means it is necessary
trygetcomponent is a lot more efficient when getting an interface instead of a normal component right?
trygetcomponent is just GetComponent with a null check
the only "efficiency" difference between GetComponent and TryGetComponent is the fact that TryGetComponent does not allocate in the editor like GetComponent does
but null checking an interface is way better than null checking a normal component right? i heard that somewhere
and how would that make any difference between GetComponent and TryGetComponent?
Comparing an object with null is going to be the same no matter what object it is
Hello fellas, I'm a programmer dabblling in unity just recently. I am making a 2d top down game and I want to have a player character shoot a gun at the enemy using a mouse to aim.
I was trying to use raycast2d to detect whether it hits the enemy or not, but I found out that the ray I cast straight up ignore the collision and will always be false. I still can't find an answer after an hour of searching and looking up documents and I think I need help
https://paste.mod.gg/ebapanlyatki/0
This is the code used for the shooting. The object has the required tag and has a correct collision box
A tool for sharing your source code with the world!
im not comparing those, im comparing interfaces and normal components
they all just object at the end of the day
your original question was "trygetcomponent is a lot more efficient when getting an interface instead of a normal component right?"
TryGetComponent is not any more "efficient" at doing so than GetComponent is. the null check, whether done as part of TryGet.. or done explicitly after Get.., will be identical
but yes, null checking an object that doesn't derive from UnityEngine.Object will be faster than null checking an object that does, and that is only because UnityEngine.Object has those overridden == and != operators to do its check for fake null
And a null check on an interface is the same as a null check on literally any other reference type
Wait, nevermind. Fake Null throwing me off again, same rake, different step
I suppose unity has to do some type of lookup first by InstanceID or whatever
that can add some slight compute time
wait so if i get an interface with getcomponent/trygetcomponent does that use the overriden == methods too?
you should give your drawray a distance btw
technically no, but i would assume that the internal methods would throw a real null back in that case if the component is already destroyed or just non-existant anyway
I think it already has a distance since it's a full vector
ehh draw ray is taking your direction normalized
its probably at most 1 in length
drawray doesn't take a direction
drawray takes a ray and an offset
Draws a line from
starttostart + dirin world coordinates.
dir being the ray and start being the offset for the origin of the ray
@atomic crater . anyway should Debug.Log($"hit : {hit.collider.name}");
oh my lord, that's it
The debug said it hits the player object, so that's why it never hits the enemy
So the hit detection works as intended after all
yeah good idea to use ignore layermasks
👍 Debug.Log(Everything);
its funny how there were Debug.log for everything else BUT the main causer
void Update()
{
if (Input.GetMouseButtonDown(3)) Debug.Log("Back Button Pressed");
if (Input.GetMouseButtonDown(4)) Debug.Log("Forward Button Pressed");
}``` just found out i can use the macro buttons on my mouse as simple developing buttons
Alright that solves literally everything. Thank you so much for pointing this out to me. I have to wrestle with a new language syntax, and it's good to hear that I just made a simple mistake
Hey, when im trying to add an onclick event to a button, i dont see my method, which has 2 parameters - in the list. But if i remove 1 parameter - i can see it. Unity does not support onclick event methods with more than 1 parameter?
that is correct
https://unity.huh.how/unity-events/method-requirements
Serialize your parameters in the script instead
You can always add listeners in your code dynamically
Hello Guys,
i am trying to update my Global Volume lens distortion via a skript.
The slider changes during runtime, but not the effect - but if i change the slider manually, it works
anyone got an idea? can post code
can post code
you should do that any time you have a code issue. #854851968446365696
!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/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
have you confirmed that there are no errors and that the code is actually running?
yes, there are no errors and like i said - the slider is moving, but for some reason it just doesent update in game
and idk why :(
I've been trying on this for 2 hours now, even with help of chat gpt
perhaps ask in #💥┃post-processing 🤷♂️
i will ask, ty
i got it working.. i didnt have the right volume mask selected in main camer->Environment
-# both of these seem to be valid
moveAction.action.performed += k => OnMove(k);
moveAction.action.performed += OnMove;
-# even without changing the method
private void OnMove(InputAction.CallbackContext k)
{
Vector2 movement = k.ReadValue<Vector2>();
Debug.Log($"Move {movement} {k.time.ToString("00:00")}");
}
i read something like "Unity knows that it needs the context so its automatically included.. my question is is that true.. and even tho im OCD and looove clean code.. something feels wrong about omitting it
Hey, it's probably something dumb but I got a script on an object with a Debug.Log() in awake and I don't get any console message, any idea how that might happen?
is the script attached to a GameObject..
Is it disabled by default?
and/or in the scene?
Note that the first one is creating a lambda expression and subscribing that. This means it cannot be unsubscribed (since you aren't storing that delegate elsewhere), the second subscribes by creating a delegate from the method group
nvm it's because I checked the thingy that makes it so the messages don't show lmao
I knew it was dumb
ohhh!..
void PlayerInputsUnSubscription()
{
// unsubscribe from player action maps
moveAction.action.performed -= k => OnMove(k);
moveAction.action.canceled -= k => OnMove(k);
jumpAction.action.performed -= k => OnJump(k);
attackAction.action.performed -= k => OnAttack(k);
interactAction.action.performed -= k => OnInteract(k);
crouchAction.action.performed -= k => OnCrouch(k);
sprintAction.action.performed -= k => OnSprint(k);
}``` so this is bologna?
Yeah I'm not too sure why a lot of the Unity examples subscribe with the lambda, but the second one implies that the return matches with the the method prototype. Oh yeah and as box mentioned if you want to unsubscribe thats a problem unless you store the delegate somewhere
Yup
yea, im pretty sure i seen someone else using ctx or context soo i figured thats what should be done.. never even questioned it
but slowly im getting the hang of lambdas and anonymous functions
Any way to make EntryIDs not serialized by the JsonUtility but still show up in the inspector?
They both use the same serialization mechanism. So you would have to use an approach that displays things in the inspector that are not serialized
That essentially means custom editors, but also plugins that make custom editors easy
😔
😸
Another alternative is to switch to a different JSON Serializer
that uses a different serialization mechanism and rules
and keep it serialized in Unity
Probably can just make another list and populate it via onValidate I would think
wouldn't that equally apply to JsonUtility and the inspector though?
I'm actually a little confused on what this pertains to. Is this to see it in the editor at runtime?
In that case you'd just populate another list that's created at that runtime
aye!! cleaned it up a bit
still chunky under Subscribe and Unsubscribe methods.. but atleast for the Enable and Disable i got a for loop doing the work
void DisablePlayerInputs(){
foreach(var action in playerActionReferences)
DisableAction(action);
}```
Hi, I'm using vcontainer, what are some ways to use coroutines if the script is not a monobehavior?
You need Monobehavior to start coroutine on. It wont work without one
You can use async just fine though..
Oh I see, what if I inject a monobehavior instance and use that to start coroutines for all the scripts that need to start a coroutine?
As long as the MB can run sure, it can work I suppose.
what exactly you need from coroutine that regular async can't do
I guess I don't know how to use regular async
instead of yield you await
Here's an example code I need to use
public void DelaySequence(float delaySeconds, Action onComplete)
{
StartCoroutine(Delay_Routine(delaySeconds, onComplete));
}
private IEnumerator Delay_Routine(float delaySeconds, Action onComplete)
{
yield return new WaitForSeconds(delaySeconds);
onComplete?.Invoke();
}
Coroutines are like fake async
if all you're doing is a delay Async should work just fine
You can probably use Awaitable too, I haven't looked into if it works without MB though
async Task DelayedMethod(){
await Task.Delay(timeInMs);
//do something```
Thanks I'll try that
You can try Awaitable too, its supposed to be a bit more efficient than Tasks in unity, only tried in MBs though.
it probably works outside too..
Hey guys I use ECS (with Entities Graphics) and want to change the material on a specific entity. Basically in one of my systems I go over all the entities that have my component, and then the children of this are the ones that actually need the changing, so my question is 2 steps, how do I get children of an entity with specific components, and how do I change an entity's Material? (I just started with ecs so I might just be expecting the wrong thing here I honestly dont know)
Probably better to ask in #1062393052863414313
using System.Collections;
using UnityEngine;
public class PortalActivator : MonoBehaviour
{
[SerializeField] GameObject portals;
[SerializeField] AudioSource audioSource;
[SerializeField] AudioClip mainmusicTwo;
private void Start()
{
audioSource.Play();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
portals.SetActive(true);
ChangeMusic();
}
}
void ChangeMusic()
{
audioSource.clip=mainmusicTwo;
audioSource.Play();
}
}
when the music is changing to second one there's a fps drop in my game . how can I fix it?
profile to find out exactly if its a real concern
wont know for sure without profiler
is there any known bugs going around in unity 6 with custom editors ?
Change the load type on the audio file to preload. By default unity loads audio on demand. For big files like music the preferred type is streaming from disk or preload if you can afford the memory cost.
https://gamedevbeginner.com/unity-audio-optimisation-tips/ I can recommend this article
private void OEnter2D(Collider2D collision)
{
}
anyone know how to fix terrible completion? Visual Studio Code
i press tab on OnTriggerEnter2D then it just completes like half of it or something, is there a setting for it?
i think so?
it suggests everything and shows errors all fine
is there a way to make coroutines' waitforseconds work in regular update/fixedUpdate functions other than having to make your own counter variable?
no because Update runs every frame so that doesn't make sense
Some very basic beginner programming logic question:
If my static class SheetHelper has a variable of the class Sheet that should aleays point to a Sheet that exists as a variable in GameManager.Instance.activeSheet; will just Sheet currentSheet = GameManager.Instance.activeSheet work? Like, I can intuitively see two things happening and I'm not sure which will actually happen:
- Any changes to currentSheet will change
GameManager.Instance.activeSheet, meaning that I can work entirely onSheetHelperto do all my modifications on the GameManager'sSheetvariable - When assigning
currentSheetasGameManager.Instance.activeSheet; I create a new instance ofSheetthat's running withinSheetHelperthat will copy all the information present inactiveSheet. It means that no changes happening tocurrentSheetwill affectactiveSheet
(PS: does the answer change if SheetHelper is not static? I was hoping to make a SheetManager too that inherits from Monobehaviour and calls functions from the SheetHelper API)
If my static class SheetHelper has a variable of the class Sheet that should aleays point to a Sheet that exists as a variable in GameManager.Instance.activeSheet; will just Sheet currentSheet = GameManager.Instance.activeSheet work?
no, because thats setting a value, you want to point to a value. for this you want aproperty.
a property is a Get and a Set function disguised as a field. in your case it would look like this
static Sheet CurrentSheet
{
get
{
return (GameManager.Instance.activeSheet);
}
}
this means when something tries to get from it, it does that logic to retrieve it.
in your case it can also be simplified to just
static Sheet CurrentSheet => GameManager.Instance.activeSheet
Hello,
I have an idea to make a voxel exploration game.
We would like the player to explore a place like in the picture (maybe not as much detail but a notion of immensity)
So a friend is creating the interior model of the cathedral. At the code level however, I would like to know what is the right way to manage this? Do I have to load the element in one go? Finally how to go about it?
I really have no idea how to import something so "big" correctly
is your friend using magicavoxel? pretty sure big models have to split into multiple parts anyway
also this isn't really a code question
I'm not sure if he uses this software but there is a similarity, but what about "split into multiple"?
In Unity, I will therefore import these multiple models, but I will have to combine them to have the final rendering, how does it work?
Forget about elements such as pillars, benches etc
I'm really talking about the structure, the building
more of a question for #🔀┃art-asset-workflow. this doesn't have anything to do with programming. (i dont really know the specifics of importing bigger models anyway)
also, magicavoxel has a maximum object size of i believe 256x256x256 voxels per object. this is far bigger than that limit so it would be split across multiple objects
I was wondering if this was the right channel, sorry
Multiple objects make up the cathedral. They'll build (model) all the pieces and import each to rebuild the scene. You wouldn't import the entire thing as one piece . . .
Not the entire cathedral of course, but the nave, I have no choice for example? how to divide it into several parts?
how do i use this outline script
I think it's for ugui only
can you able to suggest me any simple ways to add outline on 2d sprites? guides i've seen all do shader
something thats can be toggled forgot to add
Not sure if there is a shader usable anywhere but if you are comfortable writing one or using shader graph you can do edge detection to produce an outline. You do have to do some other things such as UV scaling and clamping to provide enough space however
Id share one but it's not mine
so if I want to make a make a player controller with an elongated collider but I don't want it to be pushed by forces, the only possible way to do that is to code my own movement systems with raycasts and stuff ,yea?
dang its seem adding sprite outline not simple
Edge detection isn't super hard in a shader and there are plenty of resources to teach how to do it
yea all the guides i've seen for this use shader graph, i'll look for more ways awhile, keep this as my last resort
depends, i think. kind of confusing wording there. rigidbody movement only works by pushing the object with forces. character controller movement is pretty much unaffected by physics anyway.
I would very much like character controller but it only works with a capsule collider on the Y axis
There should be a free one online somewhere or the asset store . . .
for some unknown reason my code wont work, even though i have other ontriggerenter methods as a coroutine and they all work just fine
IEnumerator OnTriggerEnter(Collider other)
{
if(canUse){
canUse = false;
if(tap){
if(tagCheck){
if(!other.CompareTag(tapTag)) yield break;
onButtonClicked?.Invoke(other);
} else {
onButtonClicked?.Invoke(other);
}
} else {
onButtonClicked?.Invoke(other);
}
yield return new WaitForSeconds(delay);
canUse = true;
}
}
No they don't
yes they do, im not calling them anywhere yet they work smh
No, they don't. OnTriggerEnter cannot be a coroutine
simple, it doesn't 
I don't believe OnTriggerEnter can be a coroutine . . .
They don't. You are mistaken
try doing this instead
private void OnTriggerEnter(Collider other)
{
StartCoroutine("coroutine here");
}
The method is probably being called regularly, but you have to call a coroutine from OnTriggerEnter . . .
damn, now i kind of want to double check this myself. that'd actually be somewhat useful if its true
are non-monobehaviour instances like this automatically cleaned up or how does that work?
holy shit, he's right
Readup on garbage collection in c#. Even if you destroy a game object or component the instances still exist till gc
im not sure i understand - yes they go to garbage collection, and then they are disposed no?
When nothing references them any more then yes they get deleted by the garbage collector.
so i would have to manually set things to null after destroying? that feels like something the method should have built in
This is documented nowhere, I am on mobile and can't test it but nothing anywhere official says this can be done
one sec, lemme try this
Not really, in this example the instance will be gc'd at some point in the future as it's not referenced anymore:
private void MyFunc()
{
List<string> mylist = new();
}
multiple people here (including me) didn't know you could do this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public IEnumerator OnTriggerEnter(Collider other)
{
Debug.Log("damn, this actually worked");
yield return null;
}
public IEnumerator OnTriggerExit(Collider other)
{
Debug.Log("damn, this actually worked");
yield return null;
}
public IEnumerator OnTriggerStay(Collider other)
{
Debug.Log("damn, this actually worked");
yield return null;
}
}
Again, put the log after the wait and see if it works
do what though?
You should read more about it as it's a c# concept: https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals
oh right, mb, i'll test it now
will do, thank you!
my understanding of gc is basically limited to brief conversations in class when doing object pooling lol
"are you still using this? no? okay I recycle it now from memory"
essentially how i understand it
but apparently destroying something doesn't make it over and done with
which i had no idea about
correct
huh, weird. wasn't the expected result but yield return null still makes the next line run
its "marked" only for deletion but not deleted yet
until GC comes with its broom and sweeps these gremlins out
SEE
but, doing yield return new waitforseconds(x) still works
Like, it actually waits or does it skip right over it and run the next line?
oh wait wtf
Put some absurd length wait in there and see
as in no one here knew you could wait return null without it throwing an error?
add me to the list, that is WEIRD
i already tried 10 seconds, it waited 10 seconds. i can try higher though
i have 2 scripts that use coroutine for on trigger enter and they both work
but the 3rd one doesnt
no, its the fact that it's trigged by OnTriggerX
usually a coroutine needs to be triggered by a void to run
afaik atleast
Unity has internal methods to Start those coroutines
oh nvm
notably
IEnumerator Start()
yeah that was my assumption
They don't need to be triggered by another method to run . . .
another internal one called by unity void async Awake()
similar to how Test Runner gives you 2 preset tests, 1 void and 1 ienumerator
thats why i tried it, and i think i saw SOMEWHERE IN THE DOCS that it actually supports coroutines....... or is it the mandella effect
Okay then, @fervent abyss I guess I owe you an apology, this is documented nowhere. I didn't just say that without checking but nothing in the documentation of OnTriggerEnter says it can be a coroutine. I don't know where you found out you could do this, but apparently it's an undocumented feature
I can confirm they do work as a coroutine . . .
correct
its okay
but LMFAOOOOOO why isnt it documented anywhere
you invented it
with magic
Dude raced backwards and found the secret level
LMFAOOOO
with start it is documented on its page
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.Start.html
huh, that's the first time i've seen that
Destroy() only removes a component or game object from use and will also unload some assets strait away. The class instances though still exist till GC.
Unity will make monos == null when destroyed for our convenience but it's a lie
Anyway back on to this, try logging canUse outside the if statement, maybe it's false when you don't expect it to be? If nothing logs it's probably something to do with the colliders or rigidbody of the objects involved
Real solution: use a debugger
im trying to debug, the method works apparently but it doesnt if check
Yeah, I saw that it was mentioned in start's, but not in ontrigger's so I assumed that meant it couldn't be done
Yeah I saw it somewhere, forgot where it was a while back. Iirc might been hidden in docs somewhere
I will say that I wouldn't—or at least—be careful when using Trigger methods as a coroutine. In my test, it ran during startup and when it was manually triggered, which is not expected behaviour . . .
fun mystery box
this is the main reason i help out in this server. every now and then someone comes in with an interesting bit of knowledge like this lol
lol nvm i got it to work
the yield break was breaking it i did yield return null and it started working
Yeah, yield break is "End the coroutine"
dont thank me guys for opening a whole new possibility in Unity
i guess im just a guy who knows a guy... [proud]
btw is there an example where a coroutine OnTrigger would be better than just doing regular OnTrigger and calling a coroutine in there?
Just in time when I pretty much stopped using coroutines xD
being lazy and not having to do StartCoroutine
Not really, just shorter
i just like keeping my code shorter.
yeah ig its cleaner, im just thinking i dont think there is a way to grab a reference to that ontrigger coroutine is there?
aside from that...it cannot be started outside of OnTriggerEnter
also you cannot Store the coroutine inside a variable
yeah
I suppose you could but it probably wont be the same one unity calls thru MB since they will run side by side
Sorry for the condescension, I even went and double checked before I did so and it turns out I was wrong anyway 
happens to the best of us 🥹
Most Unity callbacks can be coroutines. Unity automatically starts it as coroutine if it returns an IEnumerator. Only a few can’t be a coroutine. Most commonly: Awake, Update, LateUpdate, FixedUpdate, OnGUI, OnEnable, OnDisable, OnDestroy.
I could have sworn this was documented, but I guess it isn't
That said, imo a bit of a codesmell to coroutine one of them. Would advice you call coroutines from inside the method instead
That is precisely my point. The fact that you can't store it in a variable is a code smell and a bad idea for me . . .
hey, can semeone explain me why my cubePrefab dont go on the player position please ?
dont cross post
what did you do to test?
the issue is they're moving the prefab not the actual instance
can you explain why
You're trying to move an asset rather than a gameobject in the scene
not its Instantiated Clone
what am I supposed to do to resolve this issue?
store the instance in a variable to do stuff with
Instantiate returns you the cloned object
private GameObject theSpawnedObject;
void SpawnObject()
{
// Fait apparaître un nouvel objet à la position du spawner avec une rotation par défaut
theSpawnedObject = Instantiate(cubePrefab, transform.position, Quaternion.identity);
}```
theSpawnedObject.transform.position = Vector3.MoveTowards(spawner.transform.position, player.transform.position, speed);
understand?
okay I think I got it
You are moving the original prefab, but that is the object you are using to instantiate clones from. The original prefab is not in the scene. It is not the instantiated object in the scene. You need to move the instantiated object you created from the prefab . . .
-# good luck 🍀
the spawned object is a clone of the prefab that why whit the prefab it dont work
the prefab inst in the scene
Exactly. You need to move the instantiated object as that is the one created (added) to the scene . . .
i think unity needs to create a little console log for this type of stuff ;D
yes I agree
I didnt got this
its a common error... one of the first errors most people encounter
ya, i wrote it myself lol
let me show you
Yeah, you probably skipped a step . . .
just wait a minute let me try something
something is wrond whit my speed float
I have the impression that this defines the spawn point of my object that I want to move
pro-tip: for modifiers (multiplication)
its always good to start with 1 and then modify it during run-time to find the best fit for you..
b/c anything * 1 = anything..
soo its a good base-line
Use http://streamable.com to post vids or save in mp4 format . . .
btw, if you're using OBS. you can use the remux recordings button (right under show recordings) to change the recording from an mkv to an mp3
okay didnt know that
not a code issue.. works fine
what I'm trying to do is make my clone leave the spawner and make it go to the player, not the other way around
ahh well that should work fine too..
just slot in the Player's transform for the Initialization method
i dont change the position on my video, just the speed
whit these line or not?
Use Scriptbin to share your code with others quickly and easily.
heres both scripts i used in the video.. (they're your scripts just refactored a bit)
not sure why changing the speed variable affects ur instantiated object at all
the speed variable only matters when u instantiate it..
it sends the speed variable to the **Follow **script in its initialization..
after that the Spawner script shouldn't matter at all..
if you change the speed variable.. it wont affect anything until you go to spawn another gameobject
then that new speed variable gets sent to the initialization method for that prefab
It help me to understand the two script you send me
thank you a lot
for a beginner like me its very important
how can i delete the stuff in a json file but still keep the file itself?
you mean just empty the contents?
yes
you should be able to open it with a code editor / notepad and delete the contents
oh sorry i meant as if there was a way to do it through code
no problem.. thats what i try to do..
to help a bit.. but also for people to take it as an example and compare it to theirs
You can just write nothing to the file
And overwrite it
At that point, could you not just delete the file? It's not like theres anything to read from it anymore
if (File.Exists(saveFilePath))
{
File.WriteAllText(saveFilePath, "{}");
}
can i ask here what software is the easiest to learn how to make simple game's idk for example clicker or 2d game
unity?
you'll mostly want to learn a little bit of everything if ur a solo dev
- Image Software
- Audio Software
mainly
for 2D its usually Tilemaps and Sprites
#1253440741322133545 message heres a post w/ bunch of beginner resources for Unity
if ur gonna be developing w/ code you're gonna wanna start by making sure your IDE is configured and linked to Unity
!ide the most important step tbh.. if u dont have a configured IDE you can't really get much help.. its a requirement
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
if you're bad at art you can use third party assets.. the Unity Asset Store has plenty..
https://itch.io has bunch.. as well as a few other places.. i can give u a list if u want just lmk..
and that being said.. i just realized we're in #💻┃code-beginner for general Unity stuff like you're asking now you'll want to post in #💻┃unity-talk
so i can for example download tilemap asset?
100 percent..
theres tons of them
some may already be cut up and sliced
some may not be..
you'll want to be familiar with the sprite-editor and how to set up ur textures to be 2D / Sprites
im trying to figure out how to find the position of the gameobject the player collides with so the player knows which direction to fly away from, and i dont really know how to get it can someone help me lol
trying to not watch that many yt tutorials bc i end up going braindead and just copying the code w/o understanding what it does
lol
just compare it to a value
float by itself doesnt do much
if(transform.position.x > other.position.x) // if he's to my right
if(transform.position.x < other.position.x) // if he's to my left
alr
it also depends how the GameObject is moving. If it can come from any angle, then get the direction and negate it (use the opposite) for the knockback effect . . .
i am having rotation issue and for some reason its not even starting, its performing then canceling
oh alr
i was thinking about just some basic flat knockback
show code
but im just curious about how you get the direction of an object
nextpos - currentpos
subtract their positions and normalize the result, but you can google this part . . .
i did make a little gun that points torwards your mouse but i dont really understand whats happening
since i kinda just braindead copied the code 💀
very basic trigonometry
the most i understand is finding where the mouse is compared to the gameobject using mousePos - transform
and then my brain kinda melts
https://docs.unity3d.com/Manual/scripting-vectors.html
this kinda simplifies all you need to know in context of Game
alr ill make sure to read that ty
okay so if my brain is braining right which it probably isnt this is gonna get the magnitude that is going the opposite direction of the enemy
and then do i normalize this and multiply it by how strong i want the knockback to be???
you can do (a-b).normalized * force
oh
note that this is direction not magnitude. magnitude would be the distance (or length of the resulting vector). that gets the direction from collision.gameObject to this object, so any force in that direction would be toward the object this script is attached to. but then yes, normalize it and multiply it by the desired amount of force
okay so im half dumb ig
so the code works
but instead of going away from the object
it ends up going torwards the object
i havent tested the code yet im just saying what would end up happening if i just kept the code as it was
remember that direction is calculated as (endPosition - startPosition) so if you want it to go away from this object, then this object's position would be the startPosition
ah alr
so like Player.AddForce((a-b).normalized * force) ?
also how do u make ur text like that lol
`text here` to make text here
Player.AddForce((collision.gameObject.transform.position - transform.position).normalized * KBForce);
ohhhhhhhh
tysm lol
would there be a reason I can't drag some text into the script component of an object's inspector? my script has using TMPro; at the top and this is what I'm trying to drag in, it won't let me. I've also double checked that it is a text mesh pro text I'm using & also tried to assign both the object & the text component
gonna test out the code rq and see if this works thanks a lot to all of u who helped
i now half understand what im doing 💀
if its on a prefab and ur trying to drag a scene object , if thats the case it wont work
everything related to this text is a scene object
what about the objects inspector
if it changes anything, I'm not using a canvas for it (please don't ask me why...) and I just have it in the scene as you would a typical object
that sounds like a TextMeshPro rather than a TextMeshProUGUI
so you need TMP_Text // this works for both ui and non UI as its base class
ah right
Which channel do I use to ask for code help
how would I rewrite it? Do I still keep using TMPro; at the top but just change the public TextMeshProUGUI into public TextMeshPro?
just change the variable's type to TMP_Text
I think its this channel then
it's the parent class for both TextMeshProUGUI and TextMeshPro so you can put an object of either of those types in it
ok
using this code now
and it does knockback me
but like
use ForceMode.Impulse
it only happens like 1% of the time
yep, gotta make sure you're using the right forcemode. also make sure you aren't overwriting any force applied by assigning velocity each frame
I am making a simple movement system within 2D Core using Gameobject Circle and RigidBody2D
Whenever I click W, the circle doesn't move up at all. Why?
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public Rigidbody2D PlayersRigidBody;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W) == true)
{
// Debug.Log("Player clicked double U");
PlayersRigidBody.linearVelocity = Vector2.up * 10;
}
}
}
just trying to understand all of this so i can use it in future projects
basically its trying to get to apply all that force over time, in One physics frame, which isn't ideal. For that case something like Impulse is best cause it applies it all at once right away
tbh i didnt even know there were different forcemodes lol
oh alright
- have you made sure this component is actually attached to the object in the scene
- if yes to 1, have you made sure you assigned the Rigidbody2D in the inspector?
this?
Its been like that
heres a comprehensive list
have you confirmed that this code is actually running?
i am going to save this lol
its very handy
No, I could, however I hate how Adaptive Performance is logging 100 times a second
but ill try
Oop
Alr its knockbacking
but like for osme reason
its always just making it go down?
and it doesnt react when you land from above???
void Update()
is properly activating every frame, but the if statement is NOT activating as it should.
note that your if statement only checks if the key was pressed this frame, so you should not see that log every single frame, only each time you start pressing W
Yeah I know, I did a debug.log within Update() and it sent a log every frame
I then removed that log and placed it into the if statement only.
Whenever I clicked W it did not send a log
do you have any errors in the console?
If you mean
⚠️
and or
🛑
then no
wait why are you using == true
wait, you said you had the Adaptive Performance package logging things every single frame. are you using the Device Simulator to test your game? because remember, android devices do not have a W key 😉
you can just check Input.GetKeyDown(KeyCode.W) cant you?
Only scene
what does that mean?
yes, but removing the == true is not functionally different in any way
The scene tab, not the simulator tab
eh ig
did it work lmao
let me try
obviously that wouldn't make any difference . . .
lol
the scene tab is not how you run the game. it is how you edit the scene. are you runnign the game with the Game view or the Device Simulator
wheres gameview
it's the tab literally called Game
do you see that or the Device Simulator when you play the game
shocking, you're using the device simulator
Uhm, I was clicking W within scene
that doesn't matter
😭
Do I need to download some random game viewer
the scene view is not what is collecting your input. it is just showing the current state of the scene so you can edit it.
I was gone for a bit
no, you just need to not be using the device simulator if you want keyboard input.
So the issue was he was in scene view not game view?
no, the issue is they were using the device simulator which simulates an android device, which notably does not have a W key on it
Oh 💀
Never say that again
yeah let's keep the brain rot and reaction images out of here
Yipeee
next quetsion
if I can generate one
How can I check if a gameobject is standing on a floor
how efficient is new input system compared to old one?
that's commonly referred to as a "ground check" and there are probably hundreds of tutorials for how to do it. i personally recommend a physics query like a BoxCast, OverlapCircle, etc
what
i wouldn't assume there is much difference in "efficiency". what is the actual purpose of that question
are raycasts fine
idk, like is there really much difference between them?
that makes one much better than the other?
a raycast is an example of a physics query, yes. though it has no width so you might want something with more volume if you want more precise ground checks
ah, I can visualize problems regarding raycasting
the differences are mainly in how they are used and the features they support. in my opinion the input system is much better and definitely worth learning over the old input manager, and that is because it has more ways to gather input, for example you can do event based input instead of manually polling for input in your own code, or you have the option of manually polling the input if you so choose. the input manager pretty much requires you to manually poll the input with no built in alternative so you either end up with worse looking code, or you end up reinventing the input system's event based approach for yourself 🤷♂️
yeah, i just wanted to know cause idk which one is better, and also another issue i am having is that my character when it rotates, it goes back to its original facing direction when i let go wasd
and also for some odd reason, it isnt starting, its just performing and canceling
its so weird
my friend was tryna help me, and he didnt understand whats going on either
you'd have to show relevant !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/, https://scriptbin.xyz/
📃 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.
like just show you my code?
yes, that's what i said, isn't it?
whats this
read it and find out
i just paste my code in there?
The variable name makes this more confusing. rotation is the direction, or actually the heading (also called the displacement) pointing from the transform.position to the mousePos (a-b). Mathf.Atan2 gets the angle based on the provided (x, y) value, then converts it from radians to degrees . . .
Hmm, thought I sent this a long time ago?
I just copied the code but after reading this i now understand it lol
And wow ig the variables were just not well named lol
naming variables properly is a form a code commenting. the same applies to methods. You should be able to read what the method is doing based on its name and the variables within it. It helps reduce commenting all over your script . . .
Yeah
I just copied the code of the yt tutorial and they didnt really explain too much abt it so i could only rly guess
Based off of the var names
It's used for the rotation, but it's not actually the rotation. that the problem with that one . . .
another fun fact about that code: the Mathf.Atan2 is not necessary! Just assign the transform.right (or transform.up depending on it's "forward" direction when not rotated) to the direction (in this case the variable rotation)
It's not, haha. You can easily assign the direction (heading) to the object's forward-facing direction to skip all the calculations . . .
This script doesn't seem to work, any idea why? (I've used a log to check that the method is running) I did nothing in the animator except add the animation
where is the log and what is printing ?
I removed the log, it was just above the script I showed in the image and it was just a string to let me know that the method with the script inside it is being called
so I think it's an issue with the way I wrote the animator.play thing
How and where is this being called? We only have this single line. Can't really tell if there is anything wrong with the code . . .
does it matter? I already said that the method which contains that line is being called, I think it's just a problem with that line
It's in the Attack() method called from this script
and it's being called correctly because I put a Debug.Log in Attack() before the animator.play line, there is also nothing else in Attack() method
ahh nevermind, turned out to be a problem with the way I was using the animator
Did you need to provide the correct layer for the animation?
yeah, I didn't see that there was another overload so I just put 0 after the name and it worked
I was just reading about it . . .
IInteractable interactableObj;
if (Input.GetKeyDown(InteractKey))
{
if (hit.collider.TryGetComponent(out interactableObj))
{
AudioSource.clip = InteractAudio;
AudioSource.Play();
interactableObj.Interact();
}
}
InteractText.text = interactableObj.InteractSentence;
InteractText.GetComponent<CanvasGroup>().alpha = 1;
**InteractText.text = interactableObj.InteractSentence; **
it gives error when i type like that 
but its ok when i write like this, why?:
IInteractable interactableObj;
if (hit.collider.TryGetComponent(out interactableObj))
{
if (Input.GetKeyDown(InteractKey))
{
AudioSource.clip = InteractAudio;
AudioSource.Play();
interactableObj.Interact();
}
}
InteractText.text = interactableObj.InteractSentence;
InteractText.GetComponent<CanvasGroup>().alpha = 1;
in the first example, what is the value of interactableObj when that first if statement is false
nothing ig??
exactly, it hasn't been assigned, it's not even null, it's just unassigned. you can't use something that hasn't been assigned
now of course, you'll still get NREs if the hit object doesn't even have the relevant component on it, so your other code that uses that variable should also be within the if statement. then you can just inline the variable declaration instead of declaring it separately
because it is being assigned in that TryGetComponent call
with using out?
yes
oh ok tysm for the help
for now i only have player object "balloon" which flies upward, however later on line i wanna do another character that moves downward rather than fly upwards. Users can choose what type of player to play "balloon" or something else(smthing that moves downwards
i dont wnat to get my player input or player objects to be a cluster fuck so i was thinking in the future to have all type of character scripts in this 1 player object and have a class to handle checking what have the user chose to play and as a result i disable all other script components for other characters and enable only the character that the user chose
Is this a good smart approach?
my bad for the terrible english. it has been a tiring day, I am just writing quickly
What is the best way to store and load a prefab?
just the name?
or is there some identifier i can use to also easily get it, seems hard to get it with the name. I would just use a dictionary but that appears to not be serializable
there arent that many objects i need to use this for so a dictionary WOULD work if it showed up in the editor
there are serializable dictionary assets you can get, but what is the actual purpose of wanting to get a prefab by its name? can you not just serialize the reference to the prefab in the component you need it in?
there is a few prefabs you can choose frmo and i need to store which one you chose in a database and load from it
you mean i make one myself?
is that the best solution?
https://paste.mod.gg/imnmmrjpntnp/0
https://streamable.com/fvugxc
can anyone help me with my car controller 😭
A tool for sharing your source code with the world!
why is it
flying
@keen rampart Can you comment out the following?
{
Suspension();
GroundCheck();
//CaculateCarVelocity();
//Movement();
}```
See what happens.
ok
i comment out the code
is still getting flinged
Okay. Try commenting out the entire FixedUpdate() method, then.
First of all, this line: carRB.AddForceAtPosition(netForce * rayPoints[i].up, rayPoints[i].position); has me thinking about what "up" means when your car isn't right-side up. You're going to have bugs resulting from this line. Not sure it's relevant yet, but I wanted to point that out.
try putting mass at like 8000 or maybe more
ok
oh ok
oh those arent wheel colliders?..nvm then
stills getting yeeted
no
yeah nvm that only worked for wheel collider
All empty objects, except 4 with renderers.
ye
yea def check your pivot points then
aaa i just want to ask abt smth
so i have a basic enemy move script
where it just moves forward until it goes into a trigger that makes it change direction
but i also want to add a radius around the enemy where if the player is inside, it will instead target the player
the ray point?
so i just attached a collider to a empty
but now instead of changing direction when the enemy goes inside the trigger
it changes as soon as the view range touches the trigger
What is a 'view range'? Is that the collider you want to use to detect the player?
my code to make the enemy wander
yeah
Check your project settings for the collision matrix. You may have some layers that shouldn't interact with each other.
alright
I'm not too sure how to do that
how do i check that
is that this?
Yes.
I'm not using this in my project, so it being filled in won't be correct for you.
alr found the 2D
Which layer are your player and enemy rigidbodies on?
both on default
If everything is on default, everything will detect everything.
ohhh
first time learning abt this lol
i think i know what to do now
just need to give them diff layers right
and then tweak how they interact w each other
in the scene view the arrows, click each one during playmode / paused
so the layer of the detection can detect the player
but not the trigger that makes the enemy change direction
I figured. Your rigidbody2ds will also combine every collider2d in their children (not marked as trigger) to build the total "body" that they use for physics interactions, so you know.
uh so like this?
The simplest way around this is to have a child object of your enemy be on a separate layer.
ah alr
yeah thats what i was thinking
uh yeah that should probably not be all the way there
thanks a lot!
No problem. Also, disable everything in that matrix that you don't need - it'll save you CPU cycles. @obtuse ether
well i have the car a little up
in the air
is like normal until it touches the floor
and then it just start to fling
why is it so offset in the first place?
in playmode
havent seen code but you should also put more debugs
oh ok
A tool for sharing your source code with the world!
this is the code btw
im not sure but is like normal but when it collides with the ground it just starts breaking
the rays supposed to turn red when grounded but its not
did you copy this from tutorial or something ? maybe you messed something in the suspension code or something
yeah
Learn how to create an arcade-style car controller in Unity! This tutorial covers suspension logic, offers valuable insights for game developers. Get ready to build your own unique controller for arcade racing games in unity.
#carcontroller #gamedevelopment #tutorial #unity3d
-------------------------------------------------------------------...
I would look over for anything missed
it was working fine the first part
basiclly is just a temporary cube
so sounds like you might've overlooked something
at which point did it break
after i added the car model and when i added acceleration and stuff
wait hold on
i have the first part recorded
1s
this was like the first part of the tut
i had only done the
suspension part
nothing else
check your accelerationPoint is correct first
I would double check if code is same. . is still broken when you only leave Suspension() ?
guys i wanna get the InteractAudioClip value if there is one in the IInteractable interface's script but idk how to do that, can yall help me?
Here's the code:
IInteractable interactableObj;
if (hit.collider.TryGetComponent(out interactableObj))
{
if (Input.GetKeyDown(InteractKey))
{
AudioSource.clip = DefaultInteractAudio;
AudioSource.Play();
interactableObj.Interact(); // Main Function
}
what is DefaultInteractAudio?
you mean inside interactable ?
no inside this class
which classs
if there is no value which is called InteractAudioClip, it supposed play default pick up
what do you mean by
if there is one in the IInteractable interface's script
then
if (hit.collider.TryGetComponent(out interactableObj))
we get interactableObj
but i wanna get the script of this
interface
and this scripts InteractAudioClip sound
that defeats the purpose of using the interface
wdym
interface is so you just assured no matter which script implements it, you're guaranteed those methods / properties exist
cause now you have look for a specific script
oh
so i cant take the script
right?
i have a question why IInteractable is a component and we try to get this componen then?
you could but its not pretty.. why not just have a property in the interface ?
wdym
how
for the sound
how tho
can u answer?
in IInteractable put an AudioClip property
and you can check if the interactable provides that in the backing field
I mean you could probably do an is
what does "is"?
i cant put a variable to in a interface
you mean a field.. Thats why I said a property
I add to the vector the normalized vector of that vector scaled by the amount I want to change it by
public interface IInteractable{
public AudioClip MySound {get;}```
```cs
public class class SomeClass : MonoBehaviour, IInteractable{
[SerializeField] private AudioClip myClip;
public AudioClip MySound => myClip; ```
if(interactableObj.MySound != null) {
AudioSource.PlayOneShot(interactableObj.MySound); //play this sound instead```
if i dont wanna add the audio in some classes
then what should i write?
leave it null
public class TakeFlashlight : MonoBehaviour, IInteractable
{
public string InteractSentence => "Pick up Flashlight";
public AudioClip InteractAudio { get; }
like that?
or
wdym use a different component
but that can be more work / abstraction
public AudioClip SomeClip
}```
or something
I guess it depends
like every other thing
For the Unity UI toolkit, what should I target in my script so that upon pressing a button, the UI will disappear?
so i should make a new class for a audio?
How can i leave it null?
public AudioClip InteractAudio => null;
Like that or...?
leave it null as in you don't have to assign anything to it
public AudioClip InteractAudio {get;}
can i do it the way like i did?
or is it wrong?
there is no reason to do that
starting getting these warnings and I can't find anything about this online, anyone know what might be causing this?
anyone know how to fix this error?
Does anyone know why I can physically see the icon of the audioSource component on the gameObject in game?
Gizmos button in the top of the game view toolbar
Thank you :)
Hey, I got this code
Debug.Log(Mouse.current.position.ReadValue());
Debug.Log(sliderCorner[0].x + "corn");
Debug.Log(sliderCorner[2].x +"corn 2");
Debug.Log(xPos);```
Somehow xPos is always equal to the sliderCorner[0] even though the mouse position is above that, I don't understand why that is especially since the code works on another project.
Any idea why that could be?
https://paste.mod.gg/imnmmrjpntnp/0
https://streamable.com/41mmp9
hey so I fixed the landing problem
A tool for sharing your source code with the world!
but now
whenever i drive
the car goes
crazy
😭
Hello, any pros willing to help me in a thread or PM? I have some dialog script issues that was sorta working at first, but when trying to fix issues, I ended up getting less than what I had. It'll be a bit busy hence the request to do a thread/PM.
I’m not at home, but I could try from a restaurant.
Lol, thank you. #respect
Dialog Disaster XD
For some reason, the code here never gets run
{
if (collision.gameObject.tag == "Player")
{
touchedPlayer = true;
if (audioSource != null && !audioSource.isPlaying)
{
audioSource.PlayOneShot(roar);
}
rb.velocity = new Vector3(0, 0, 0);
}
else
{
Debug.Log("collided with something");
}
}```
I want the trigger to run this code when the player touches it but the debug.log never happens
thank you lol I had it inside the update() function
works now
Wouldn't it be easier it you just download a free premade controller
Also use CompareTag to check tags, it’s more performant
i'd check that Acceleration point.. make sure its perfectly centered..
i just glanced at the code.. but looks like u got 2 forces acting on it..
an initial force.. and a reactive force.. could make it unstable..
i'd also try using lower values and see if that makes any difference.. or atleast slows it down enough for u to visually see whats going wrong
hey thank you for the help
i just realized
i forgot to freezethe x and z rotation lol
that'll do it 😉
ye thank you :0
if u want the cars front end to raise and dip from torque
you can get by by tilting the graphics
(in local space)
yeah i was wondering about that
since the back tire
are floating
if i go on a ram
try playing around with the wheel collider radius' and the suspension lengths and whatnot
should be able to get the tire to just clip into the ground
you have over a thousand errors
I accidently made a gameobject particle system that is supposed to look like dust effects when the player leaves the ground, are there ways to convert it to a component or am I cooked
There is a particle system component on it
what
The gameobject isnt a particle system itself, it has a particle system component on it
