#💻┃code-beginner
1 messages · Page 105 of 1
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
oh i see so i need to put the loop in the coroutine?
your sprite object has a navmesh agent on it. that means it is moving (mostly) independently of the parent object
so, Have i to put the navsmesh in parent?
why do you have both a navmeshagent and a rigidbody?
but also yes, it should be attached to the object that you want to actually move
because the tutorial say it to put for collision and IA movement
the tutorial told you to put a rigidbody on the parent object and a navmeshagent on the child object? 🤔
yes
Hey, how can i play a sound that continues playing after i disable the gameobj with the Audiosource
don't make the AudioSource a child of the object you are disabling
You cannot. Use a different object than the one that gets disabled
alr thanks
So, navsmesh must to be always in the same place that rigidbody and box collider?
unless your rigidbody is kinematic you shouldn't even have both a navmeshagent and a rigidbody on the same object
may you explain me tecnically why? (my game is oly 2d, I don't know if matters)
@slender nymph great, talking about good patterns, to create enemies, is better to put everything inside the same object like I did with player or separated? if I put separated, which is a best pattern for that (talking about components inisde?)
it really depends on how you want to organize everything. whatever moves it should be on the upper most object that needs to move
public void OnBrake()
{
braking = true;
}
i have this code that makes the car brake when pressing the bindings for this action. how can i make it so that braking turns false once the player stops clicking the binding?
or is there a way to check if is braking?
something like if(inputAction.brake) ?
you're not really providing enough context for that OnBrake method. but if you are unsure how to use the input system then read the docs pinned in #🖱️┃input-system
lovely. then OnBrake is likely being called each time you press the key as well as each time you release it. of course since you're using SendMessages you don't really get any of the useful info about the input action to determine the current state of the input
Why is the sphere teleporting down the cliff and not slowly falling like in the beginning?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] float Speed = 6.0f;
[SerializeField] float gravity = -30f;
float velocityY;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
UpdateMove();
}
void UpdateMove()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
targetDir.Normalize();
velocityY += gravity * 0.5f * Time.deltaTime;
Vector3 velocity = (transform.forward * targetDir.y + transform.right * targetDir.x) * Speed + Vector3.up * velocityY;
controller.Move(velocity * Time.deltaTime);
}
}
so i should just use braking ^= true; ?
you never reset your velocityY when on the ground so it just constantly accumulates
it works now thank you so much!
Ah i see thank you!
Anyone know any good 3d player controller tutorials
there are hundreds of them on youtube.
or just use a premade one
I looked on youtube but most of them use input x and y axis which doesn't allow changing keybinds
converting it to actionmap isnt that much different
I have a controller that i programmed but it feels weird. I feel like I am having to set speeds way higher than I should just to get the character to move at all and it also is inconsisten and jumps in speed occasionally
you're still using a vector2
Hey, guys! Is there a way to DontDestroyOnPause a game object rather than on load?
I mean if I want to pause my game and I want music to be stopped and after that when I click continue button to play it again not to be repeated
ok thank you. Are you able to also look at this and tell me why it may be inconsisten in speed sometimes?
just pause the audio source instead of stopping it
probably should not be mixing Time.deltaTime with rigidbody movements
that actually looks fine since they appear to be increasing the values over time
oh really? I thought you were supposed to use time in player movement
you don't use deltaTime when applying physics. you also don't multiply your velocity by deltaTime. with the exception of increasing velocity manually over time, but you only multiply the increase by deltaTime before adding it to the velocity, never multiply the velocity itself by deltaTime
oh true You're right thats only going on speed increase
So in my case take it off?
or leave it since it is on an increase instead of directly on velocity?
i don't have the full context so i don't know. what i see seems to be fine to leave the deltaTime multiplication in. however those extra 100 multiplications seem pretty sus and make it seem like you're not actually increasing it over time, but rather just adding to a zero vector and resetting the vector each frame
ok makes sense
thanks guys]
Hey! How to pause my audio is there a method that does that? I mean to pause the audio source I have to set its timescale to 0 right?
have you looked at the !docs for AudioSource?
great! if you've looked at the docs, the surely you've found the Pause method
By the way, I have audio mixer in order to manage my sounds in game. Is it the same for audio mixers, I mean pausing and unpausing?
the audio mixer is irrelevant here if you just want to pause an audio source
ok!
API usually for code like Audiosource
Alright, thanks!
Oh, how handy and cool it is there is a method actually for pausing and unpausing audio source!
guys, how would i use the rb.addforce on a character controller??
You don't mix character controller with rigidbody
You would not
ik but what would be the way to replicate it
But these are 2 different things
Math that you plug into .Move()
Learn physics and implement it yourself 🤷♂️
Or just use rigid body 🤷
you mean rigid body with character controller??
i mean i could do the player movement with rigid body
No
No i just said you don't mix it
You cannot do that.
alr ill remake the player movement with rigid body
They mean INSTEAD of a CharacterController
thats not a very good answer is it
Your approach is not very good so
It's the ONLY answer
You asked he answered 🤷
I am having a lot of difficulty with this code, I am trying to make a script that plays an animation only one time, and after time gives control back to the player. My mind is beyond this code, it just looks like spaghetti
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Looks like good case for animation event
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Where at the end you restore the things you want
the animation doesnt even play tho 😭
its either I have it where it can play but you can play it a second time (not what I want)
or it never plays in the first place (def not what I want)
the built in CC isnt really too good, you should do as suggested above to use rigidbody instead.
But to answer your question, if you had to move a CC in this way then I would have another vector on your movement script which handles external forces. Every time you move, you would move by (regular move) + (external forces). Then you can handle reducing the external force however you want every frame, since this is already apart of the update loop. Instead of the rb.addForce, you would call some method which adds to your external force
would this work for hiding a mouth when talking?
void update()
{
if (voice.IsSpeaking)
{
mouthopen.SetActive(true)
}else
{
mouthopen.SetActive(false)
}
if (voice.IsSpeaking)
{
mouthclosed.SetActive(false)
}else
{
mouthclosed.SetActive(true)
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
No need for 2 ifs
ik
mouthopen.SetActive(voice.IsSpeaking)
mouthclosed.SetActive(!voice.IsSpeaking)
Short form
its to hide the closed mouth when talking and to show open mouth
this good?
cs
void update()
{
if (voice.IsSpeaking)
{
mouthopen.SetActive(true)
mouthclosed.SetActive(false)
}else
{
mouthclosed.SetActive(false)
mouthopen.SetActive(false)
}
}
Yes
This is better tho
ok
even better would be an event or something and immediately reacting to the voice beginning and ending to speak rather than constantly checking in update
good?
No, it is not at all formatted that way. Not good
what do you want from me
ive been here for 5 mins
To read!
why is my script refusing to take my animator
Just to be respectful to others and follow the rules. Not much
what animator are you trying to drag in?
its already tied to another script, dont know if thats the issue
i was being respectfull
im just comfused
Are you trying to drag in the animation clips?
no the animation controller itself
player_controller
Just read the bot and what it says 🤷♂️
That's all that is asked of you. It is very simple
that isn't an Animator component which is what your variable is looking for
how would i define an animator controller
why would you need to?
your animator controller goes into an animator component which is what your code will interface with
do i paste the link to gdl space or smthing?
im confused then
public void RandomCode()
{
DoingTheStuff()
}
Yours was short enough to just format
And it's just for the future. No need to repost your code
😎👍 got it
- Add an Animator component on your player
- Drag-drop the Animator Controller (the asset in your project files) into the Animator component you just created.
- Reference the Animator component into your script
thing is i already have an animator
where
in my main player control script
wdym in the script? Animator is a component
That's a variable to fill in
You haven't put anything in it
Hence the "(None) Animator" that is displayed
this is what my animator looks like now
show the animator component
Animator is just like your script, or a Collider, or a Rigidbody. It's attached to the object
What you're showing here is the asset, not the component
im using 1d movement which gets flipped accordingly based on cursor direction
That's not it
Click AddComponent in the inspector of your player, and type animator
this is not relevant to what is being asked of you right now
ok now i see it
hey can some help I have a small game I need to add a gun to the camera in first person 😄
if you have a question about your code then you'll need to ask it
https://dontasktoask.com
-.-"
have you looked at the !docs for the Animator class?
does someone know how I can work a project from2 diffrent computers using Github. I made a github account and a repos on the first computer using Github destop. I then cloned it on the second computer. everything I do on both get sent to Github but the changes don't get put on the computers.
you have to pull the changes
Push and pull. 
i pulled but I dont see any changes in the history
Push from the computer that changed stuff, pull on the ones that need stuff
are you certain you are working in the same repository?
I am working in a cloned one
Are you certain you pushed and not just committed
process for syncing changes:
Make Change > Commit Change > Push Change > Pull Change on other device
oh it worked. I just had to push again on the first computer. thank you!
can somone recommend a tutorial for building a wave genrator for enemies in a 2d top down game
Copying your exact sentence
that a 2d tower defence game
but yh i did that
In this video we will make a wave spanner. Lets Get Started
So we will make a spanner in which we can have multiple waves and in each wave we can set up how many enemies we want to spawn , what type of enemies will be there in a particular wave and how fast we want to spawn those enemy.
Then after we have spawned all the enemy in a wave , we wi...
im watching this vid currently
Why does it being a tower defense game matter? It's a wave spawning tutorial
fair point
can i ask question about animation here?
if it is code related, go for it. otherwise there's #🏃┃animation
-.-" how do I attach an object to the camera in unity like a gun
Make it a child object of the camera
i did and I still cant see it in the camera when i play
but it is attached
Is it positioned in view of the camera
uh
how the hell does this happen
- this is a code channel
- is appears your animation is very short
i dont know how but for some reason this exit time transcends time itself
Not really. It's 0
yeah it's so incredibly small that it is effectively 0
How do I get my character to jump only once?
here is my code:
Rigdy.AddForce(0, upwardForce * Time.deltaTime, 0, ForceMode.VelocityChange);
} ```
start by using GetKeyDown instead of GetKey. then you probably also want to do some sort of ground check
thx
You probably want to remove deltaTime from the equation too
but If I were to want him to be able to double jump how would that work?
kk thx
You could have an int like jumpsLeft and set it to 2 whenever you hit the ground
And when you try to jump, you check if any jumps are left
thats a good idea thanks
If yes, subtract from the counter
Just playtested
when using Input.getkeydown if I spam click the player still flies any way to prevent this
Thanks
Whats a good way to learn? Can anyone recommend any specific courses or anything?
I used brackeys but Im also new so you shouldnt take advice from me
Forgot to read that last part
thanks
can I have an if statement inside of an if statement?
yes
thanks
in case you're wondering, this is because the jump is an instantaneous thing
you aren't gradually accelerating the player upwards by applying force every frame
deltaTime is used when you're doing something every frame, and need to make sure you do the right amount each frame
ngl I just copy pasted the other code so didnt really pay attention to the deltatime thing
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwordCollision : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
Debug.Log("Collision");
// Check if the collider belongs to the "Enemy" layer
if (other.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
// Handle enemy hit logic here
Debug.Log("Enemy Hit!");
}
}
}
why doesnt this work?
it gets activated during animation
hey I have a zombie chasing me but it is flying it does nt know where the ground is...
the code looks like this
public class Zcharacter : MonoBehaviour
{
public float moveSpeed = 3.0f; // Adjust this speed as needed
private Transform playerCamera; // Reference to the player's camera
void Start()
{
// Find the player's camera
playerCamera = FindObjectOfType<FirstPersonController>().playerCamera.transform;
if (playerCamera == null)
{
Debug.LogError("Player camera not found!");
}
}
void Update()
{
// Chase the player if the player's camera is available
if (playerCamera != null)
{
// Move towards the player's camera position
transform.LookAt(playerCamera);
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public class Zcharacter : MonoBehaviour
{
public float moveSpeed = 3.0f; // Adjust this speed as needed
private Transform playerCamera; // Reference to the player's camera
void Start()
{
// Find the player's camera
playerCamera = FindObjectOfType<FirstPersonController>().playerCamera.transform;
if (playerCamera == null)
{
Debug.LogError("Player camera not found!");
}
}
void Update()
{
// Chase the player if the player's camera is available
if (playerCamera != null)
{
// Move towards the player's camera position
transform.LookAt(playerCamera);
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
}
}
and where are you telling it where the ground is at?
because right now all you do it make it point at the player and go exactly that direction
depends on what you mean by "add that"
add that o the code some how
what exactly do you think you need to add based on my previous statement?
tell it to stay on the terrain ;D
you need physics/gravity of sorts
I have that for my player but i need o have that for the other characters
well with this you're alwyas flying towards player anyway
transform.LookAt(playerCamera);
Physics.Raycast
nah you just need to set the target to a variable and ajust the y post to your own
but if I go up on a hill it will go under the hill
are you doing 3D ? just use a navmesh
3d
so use a navmesh
Jumps == false;
}
``` This is my code. How do I make Jumps false without triggering the error message " only assign call and increment could be used as a statement"
Jumps = false
oh
that's also not the way to do a ground check
you're going to want to look into using physics queries like Raycast or OverlapBox or something to do a ground check rather than comparing the object's position to a different object's position
ok
i go sleep cya
I am following brackeys basic tutorial to get my grips on the engine again and on the 5th tutorial about collision he sets up a public variable to put the movement script in
why do i need to write the script name then the variable name
just for me to set it manually outside
does it need to have the script name there?
That's how all variables in C# work
you always put typename variablename;
C# variables all have types and names
sorry maybe i phrased it wrong
Yes your phrasing is part of your misunderstanding here.
he uses the same name before the variable name as the script he uses
Yes because the name of the script is the name of the type
when you create a class you are defining a new type
It's not just the script, it's the type.
In C#, you have to mention what type a variable is.
i woludda thought i would have done something like Script before hand insted of saying the name of one of the scripts
it's exactly like when you do int x; int is the type name, x is the variable name
No because you need to know exactly which script it is, so the compiler knows which variables and functions it has
C# don't just let you assign whatever you want. You don't assign it to an int then a string.
You promise that the variable will only be of that type.
but then why do you need to drag it in outside of the editor
because you could have 1000 instances of that script in the gamew
you need to tell it which instance it's referring to
If you have a Cat script, you could have 25 cats in the scene at once
this tells it which cat you mean
huh alright i kinda understand lol, i have used GMS for 2 years so its a bit of a change
thanks for the elp
GMS definitely has instances of things
yeappers
this is a fundmamental concept in programming basically
In GMS, I think you get instances by referring by ID. I'm not sure if that's correct.
brakeys doesnt explain it very well as he is doing it, for me to learn i gotta know why certain things needs to be done
yeah but in this instance its reffering to itself so it wolud be a whole diffrent thing
Brackeys is not the best for learning the basics.
He expects you to already know some c#
just need fo find footing then ill branch out on my own
that is absolutley not true lol
Well, that's what you can tell from their tutorials.
What? 
i am watching the begginner basic one
he has constantly explained stuff very simple stuff like variables before in this
he just doesnt for some things
he said that the basic movement might be hard for the person watching
Okay, but their tutorials are still not great for a beginner.
anyone who knows even a little but of c# woludent find it difficult lol
I'm not saying it's difficult. It's specifically because he omits things like that.
brackys has actual c# tutorials too
It's still easier to learn C# first before unity.
It should be easier to separate Unity's magic and normal C#.
you can manage a bit with basic coding knowledge but if you don't have that oop knowledge of classes, objects, and constructors then you're not* going to get very far beyond flappy bird.
so when i am going to refrence a script i need to declare it first as a vairable at the start then i need to drag and drop the same script into it in a public thingy. Still dont know why there isnt just a "script" thing then you can drag and drop it
but i shall adapt
Anyone know why my laser just freezes (along with my ship) the second I left click? I know without enough detail it might be hard so if you need the script just ask. Thank you
You can pass objects through method arguments or just declaring the field yourself.
Not everything has to be done through drag and drop.
another thing too is not understanding the concept of this monobehaviour class and why we don't have an actual constructor.
that'll bite you in the butt later
If the problem is the script then you should post it
actually I just figured it out thanks though
Hey guys this piece of code: cs playerBarShoot.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition); I am using to make sure my playerBarshoot follows my mouse position. Woirks, but as it is UI Image and it needs to be as I am using the filled option to fill every time I shoot.. Like a timer between shoots. But its following inside the UI view. I want it to follow in the screen of the player, not the UI. Any ideas?
eh, if your screen is larger than the UI then probably need some normalization of coordinates
hmm.. yes its bigger.
wayyy bigger hahaha
is there a way to create a filler imge like UI image that is not part of the UI ?
is there a reason you've the player as a UI image and not just in the world?
or w/e you're trying to get follow your cursor
well.. i need the Filled option on the Image UI
can I get that without being an UI image?
my solutions usually stink by doing masks and shaders, but you can probably do like a world canvas perhaps
hmm its too much just for a small feature i want to implement
is there a way to change my ui size and fit my screen size?
hmm true.. scale might work.. thank you
Hey guys so right now when I click somewhere my object looks right down into the infinite void of space, and all I want it to do is rotate toward where I click and not just be pointing down all the time. If I lock all of the rotation it doesn't rotate at all, but if I don't lock one of the axis is points downward. It is probably because of this part of my script where I have it look at where I point, but idk how to make where I click not some area way below the object if that makes any sense. Here is a part of my script where I have it set to look in that direction.
so the z rotation is changing?
debug your target position that it's correct and then your transform rotation
ah, maybe want to be explicit on the rotation axis on the lookat I think
use the overload method
Ok so it says that if I leave out the worldUp parameter, the function will use the world y axis...which is what it is doing. I probably need to add the worldUp parameter, but I have no idea how...
you ideally don't want to be using transform.LookAt for 2d. just set the object's transform.up or transform.right to the direction to the mouse
yea but this is in 3d because I thought it would look cooler and I don't want to restart everything in 2d. Can I still do that?
then you need to view this https://unity.huh.how/screentoworldpoint
unity is a 3D engine, but there are tools for 2D but if you do want that depth then stick with 3D
2d is still 3d. you just typically ignore the Z axis for many things
yeah true, but I guess you can cut down on collider types, but not sure if say a circle collider is more performative from a sphere collider because math
I would assume so though
I find it interesting how sphere colliders are generally considered performative, but a cylinder collider is a big nono
It makes sense when you consider that a sphere collider is just a distance check based on radius from center
A cylinder collider has a lot of considerations for when something is in bounds
I remember reading something about the cylinders and how it's just much more performative to make a capsule collider (cylinder base and spherical ends)
basically because math
hey guys. Using this ```cs
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = transform.position.z;
transform.position = new Vector3(mousePosition.x, mousePosition.y - 1f, mousePosition.z);```to make a bar follow my mouse.. it works.. but i feel there is a delay.. I mean very small but if I move the mouse bit faster the bar takes mili seconds to follow and I can see that.. tried fixedUpdate got it worst.. any advices?
Cylinder collider is a MeshCollider, right? It's not representable by simple mathematical functions like capsule or sphere
Though for overlaps, it could basically be a capsule check + box check combined
But calculating contact points etc. would be tricky
Was more that I was suggesting a cylinder collider as a primitive but apparently it's not recommended
or at least what I got from scouring some stuff
The hardware cursor generally displays faster than applications detect/render, you're likely just experiencing that.
You can switch to a software cursor when you're dragging, which would make them appear in sync because Unity would be rendering it
What do you mean software cursor ?
Thank you
So my player controller script works just fine until I add a script to my enemy object. When I add the script and press play nothing works. Anyone know why that is?
You will need to elaborate + post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Post code from all the scripts or...
So far you've provided little to no information, I don't know what scripts you have
Well when I add a script (or any script) to another object in the scene besides my player object, everything in my player controller script appears to do nothing at all. Same for all of the other scripts. If you want to see my player controller script I can send it but idk if that's what it is.
Well, that's not normal behaviour, so yeah, some more context is required
Are there errors in the console window? That's the only thing that could help give answers without any code posted
Here is a screenshot of my playercontroller script because I am struggling figuring out how to copy from the website:
You paste it in, click save, and copy the new url
ok thanks should I do that with all of the scripts?
that relate to what I am trying to do at least
Add some logs/use the debugger to find out what code's running
You should put some Debug.Logs into various methods. Nothing here should cease to function based on another script
Edit: 🦥 what vertx said
because there's nothing immediately obvious that could cause it to not work
Why is camera.current not fetching the camera that is currently rendering?
Is it currently rendering? Because it's only set when actually in the render loop
I'm trying to fetch the camera, that the player is currently using.
yes
Yes, there is only one camera in the scene currently that is rendering, which is the camera that the player is looking around with.
Most of the time you will want to use Camera.main instead. Use this function only when implementing one of the following events: MonoBehaviour.OnRenderImage, MonoBehaviour.OnPreRender, MonoBehaviour.OnPostRender.
?
And are you using the events that it specifies, ie. the ones where the camera is currently rendering?
No
Great, then don't use that property then.
So how do i check the current camera in use?
You don't. Multiple cameras could be rendering.
Most of the time you will want to use Camera.main instead.
Sounds like you should look into Cinemachine if you're juggling multiple cameras
scalling wide should i use get set operator to trigger a function or invoke an event when the variable or an object is change or created
An event invoked in a setter sounds good imho
Though it really depends on the exact use case. If there's more logic in the object that owns the property, maybe a setter method would make more sense.
hey guys,. i have this IEnumerator.. but even if I change run time the value of lifeRegenCap , and the value is being changed because I see it on debug.log for some reason the time seems not to change inside the WaitForSeconds. Why is that? ```cs
private void LateUpdate() {
StartCoroutine(LifeRegen());
}
private IEnumerator LifeRegen(){
Debug.Log("LIFE CAP: " + lifeRegenCap);
if (playerCurrentHeath < playerTotalHP){
playerCurrentHeath += lifeRegen;
OverHeadDamage _dmgOverHead = Instantiate(_overHeadDamagePrefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity);
_dmgOverHead.meshProText.text = "+" + lifeRegen;
_dmgOverHead.meshProText.fontSize = 20;
_dmgOverHead.meshProColor = Color.green;
if (playerCurrentHeath > playerTotalHP){
playerCurrentHeath = playerTotalHP;
}
}
yield return new WaitForSeconds(lifeRegenCap);
} ```
Don't start a Coroutine in an update function without a check to see if it's already running. You are just creating a new coroutine every frame
The waitforseconds is at the very end, so nothing is delayed. What is the point of it?
All of your code before it happens in one frame, then that instance of the corutine waits, then ends.
Keep in mind, you can have as many of these coroutines running concurrently as your computer can handle (like vertx is saying)
Hmm ok, thank you guys, I will try something else.
just wanted to control a life regen per second. and coroutines sounds the good way to go.. not sure
I would say coroutines still are, you just need to do it differently.
Maybe use a while loop with a yield return null inside and add deltaTime * someMultiplier to the health so it smoothly increases
Of course you need a bool at the beginning and end
will try something here. thank you!!
var go = Instantiate(FloatingText, transform.position, Quaternion.identity, transform);
how do I instantiate this GameObject 1f higher on Y axis?
transform.position + Vector3.up
lemme try this 🙂 brb
nope, still doesn't work somehow
still spawns it at 0, 0, 0
You are spawning it as a child. So the inspector shows local position
No sorry, not quite true with that last part
can you elaborate on this pleaase? what do I put to offset it then?
0,0,0 is the parents position. So you CAN offset it. It just will show differently
Sorry, I misspoke before
why my debug.log return null exception?
i did set public float shootSpeed=10f; in PlayerAttribute
float is never null
PlayerAttribute is the null thing there
Do you have that component on the same object as this script?
nope
Well that's why it's null
GetComponent gets a component on the same object it's called from
neat i learned something new
You'd have to show the code. What vertx said should be right. It should have shown 1,0,0
weeeell..., hi there!; I have an slight issue that I don't know if you have stumbled with
1 min
I am making a Top Down 2D project. In the game I can walk into a door and it would change the scene to a House Scene. Now I have multiple houses that are in different locations. I am wondering how I can make them change the Scene back to the "Town" scene that all the doors lead back to, but right in front of the door that they went into to get to the other scene. (If more information is needed, let me know.)
I have this code that just is a base move object in a loop between two positions script, but it does some weird things when it has to move in two axis if the scale/rotation is not the default one like reaching one of the axis position sooner than the others; do you know why that might be?
can someone help me with this error? error CS1061: 'AnimationEvent' does not contain a definition for 'stringParameter' and no accessible extension method 'stringParameter' accepting a first argument of type 'AnimationEvent' could be found (are you missing a using directive or an assembly reference?)
This doesn't look like your code. Are you seeing this error in Unity?
Are you using Visual Scripting?
Where did you do the offset?
it didn't work anyways
Pass/cache the information about which door it is before exiting back to the town. Then use that information to position the character properly.
Do you know what is the second parameter of the instantiate you use?
.... well maybe because it was done wrong. That was the point of asking to see how you tried to do it...
1 mom again
Share code properly and provide some visual explanation of the issue(a video recording?)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You want to have a floating text in screen space while the gameobject in world space?
Ah, it's a rect transform
yea visual scripting 1.9.1
If I share the code, could you explain more on what you mean?
y... does it change much? 🙂
If the package has any updates in the package manager, install them. If not, try to change versions to something else.
That package version must not be compatible with the Unity version you're using
It changes everything, yes.
You probably want to use a worldspace TextMeshPro
Otherwise use anchoredPosition iirc
Like this...? https://paste.ofcode.org/AHj8mhKNez6nZU7dTqEWJ2
sry first time here, I don't think I have any recording apps at hand though
will try, 1 min
What part exactly is unclear?
Yes, but without understanding the issue, we can't help you even with code.
if (collision.gameObject.TryGetComponent<PlayerInput>(out PlayerInput s1)) {
SendToScene();
}
}
``` This is attached to the Door Object and has a BoxCollider2D. When the Player Collides to it, it will change Scene.
```c# private void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.TryGetComponent<PlayerInput>(out PlayerInput player)) {
DoAnimation();
}
}``` This code is again attached to the Door Object, but is a child of it. It has a PolygonCollider2D and detects the Player before.
How would I implement what you are telling me to here?
There are many ways, but for example, store the position of the door in the outside scene in a game manager that is persistent between scenes. Then use that position when you transition back to the outside scene.
Create a Object, Call it GameManager and add a script that changes the position of the Player Spawning into that Scene when the door is collided with. - Is this similar to what you are trying to tell me?
You usually should have a game manager or other similar script that manages the overall flow of your game.
It has to be able to persist data between scenes. So for example DDOL.
Okay, I'll try that out. Thank you!
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Transform playerSpawnPos;
private void Awake() {
Instance = this;
DontDestroyOnLoad(gameObject);
}
}``` Just the GameManager Script
This code is inside another Script on the Door Object*
```c#
private void Start() {
newPlayerSpawnPos = GetComponent<Transform>().GetChild(0);
}
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.TryGetComponent<PlayerInput>(out PlayerInput player)) {
GameManager.Instance.playerSpawnPos = newPlayerSpawnPos;
}
}``` When the Player collides with the Door Animation Collider which is pretty big is radius, it will set the GameManagers playerSpawnPos to the new Position. This works and teleports the player correctly, however it only works within the scene it was changed it. After I change the Scene it says the Transform is missing. I'm guessing it has to do with the fact that the object isn't found in the scene. How can I fix this?
Make the playerSpawnPos a Vector3 instead of a Transform
That is Smart! You are correct, thanks!
The value will persist, but yes the Transform is destroyed unless THAT object is also put in DDOL
Okay... I just went, made empty game object with transform instead of rect transform, attached my thing to it, now it works liek a dream 🙂 Thank you for pointing out that the thing is about recttransform )
ok, so I think I figure it out why it is failing; if someone is interested is cause it is moving in a local space instead of global so when rotated it moves in a different vector
Reference image
I want the coordinate at which it moves to be local though, any way of solving this?
How do I make it so that when two objects collide they are both destroyed?
Awesome, glad it works!
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
Destroy(collision.gameObject);
}
private void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
Destroy(collision.gameObject);
}
thanks
try using OnTriggerEnter if it doesn't work with what you have
This is the 3d version. Use the 2d one if that isn't right
Why is my GameManager duplicating on returning to a scene? I am using DontDestroyOnLoad();
Whenever you load the scene, that object is in it. Since the object is never unloaded when you leave a scene, the old one is still around when the new one is loaded
Also, don't just do OnTriggerEnter if it doesn't work. Only do that if you want to work with trigger colliders. It could be not working for other reasons
Whats a simple Solution?
Have your DDOL object check if there's already one of itself in the scene on start. If there is, destroy itself
Proper static accessor setup, where you check if the instance is null. If not, destroy itself
I think vertx shows example code here
https://unity.huh.how/programming/references
Under singletons
Edit: yeah, the first example code there
So I'm trying to get better at decoupling code, it's something I'm struggling to find ways to get around. For example. I have several objects in my game, like a dash pad for instance. This dash pad has a script on it that gets a reference to the player's speed so when the player enters the dash pad, it can manipulate this variable. Is there a better approach to this or is this pretty common practice?
What's a "dash pad"?
It's fine if it fits your purpose. If you have many objects like that that manipulate the character speed, you might want to have a speed modifier for that in the character and get it from a trigger zone or something.
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[SerializeField] GameObject player;
Vector3 offset;
private void Awake()
{
offset = new Vector3(0f, 0f, -10f);
}
private void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}
Player has rigidbody based movement with AddRelativeForce.
The environment is zero gravity and the camera is just supposed to follow the player. The movement is nice and smooth if I make the camera the child of the player, but its jittery when I use this script and there is some weird ghosting of the background.
2D btw
That would indicate that your rb is not interpolated properly.
Also, did you try using Update instead of late update?
I used update and nothing happened
I also set the rigidbody's interpolate to interpolate and it didn't work
I have had several jittery issues, try mixing, late update, fixed update and Interpolate/Extrapolate in the rb component
Usually combining those eventually gets the result I want for me
okay
nothing seems to be working
in some cases the background is jittery, and in other cases the player
I had this issue before. Can't remember how I fixed it but start by checking the following:
• Make sure rigidbody addforce or any rigidbody movement is handled in FixedUpdate()
• Make sure camera follow is in LateUpdate()
• Try using Rigidbody.MovePosition instead of AddForce or AddRelativeForce
playerRigidbody.MovePosition(targetPosition);
I will see if there was something else I missed.
When I had the same issue like a month ago I found a solution somewhere on Google.
Then something is breaking the interpolation. It's hard to say more than that without any context.
im receiving these errors and i'm not sure where i'm missing them. visual studios says there are no issues. will post my code in next message
But to put it simply: don't move or rotate the object in physically incompatible ways.
anyone able to help me pinpoint my errors? i've been at this for awhile and i think lack of sleep is getting to me 😅
If visual studio is not saying anything, it's not configured properly.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Also just looking at the lines that the errors point to is enough to see the issue. One is that the curly braces are not where they are supposed to be.
is it saying lines 5 and 46?
i was used to VS saying what lines then i had to redownload it and i think thats why its not configured
Follow the config guide above.
I did it. Its still saying no issues in VS but I have 4 in Unity.
Ya you gotta install extensions. You can find the Visual Studio Editor package in your Unity Package Manager.
Gotcha.
Then it's not configured.
Share a screenshot of unity workload in vs and the external tools in unity if you still have the problem.
@stark sonnet
Here is a basic walkthrough for correctly installing/configuring Visual Studio & Unity:
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows
If you prefer to use VS Code with Unity, here's a walkthrough for that:
https://code.visualstudio.com/docs/other/unity#_set-vs-code-as-unitys-external-editor
It's the same as was linked to them earlier...
Might have to download the latest .NET Framework also
whats the best way for store lots of dialogue text? Do you just have a class that has a gigantic 1000+ size preset array, and then lookup the text at runtime as needed?
okay so i got it configured. turns out the entire script i learned in this tutorial is completely broken from what I'm seeing 🙄
thanks for the help guys!
oh! and one more question. anyone know how to turn off the suggestion/autocorrect thing? it keeps autocorrecting me to things i don't want typed and I'd just rather not deal with it
The first number (5 in your case) is always the line thats producing the log, and the second number (46 in your case) is the number of characters, so if you counted 46 characters, on line 5 in your camera controller script, youd find your error - I always ignore the second number and just focus on the first, usually itll be clear enough that I dont need to count the letters
thank you! i didn't know that! VS normally just states the line. I never knew how to find it through Unity
Yup, and in most cases, you can also double-click the message in Unity, and it should highlight it in VS
I believe this is called "CodeLens" or "IntelliSense", this may help: https://learn.microsoft.com/en-us/visualstudio/ide/reference/options-text-editor-csharp-intellisense?view=vs-2022
Though tbh, I always find it a useful feature to have enabled, when you get familiar with it, it can really help save time typing every letter all the time, though while learning, I can see how it can get a bit intrusive
i was wondering why this wasn't working it works at the center (0, 0) but whenever i move it away it will just shoot away from the center not the game object go against if anyone has a simpler way to make a simular acting projectile feel free lol im open to ideas
your !ide is not configured. Configure it first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it was
it also broke bc of an update
ive been coding without it
its fine
you need a configured ide to get help here
server rules, configure your ide
Lol, you really like to shoot yourself in the foot.😅
Just configure it, it's not hard
Whats the advantage of defining a new list outside of a function in the global variables?
You're really shooting yourself in the foot by not having a properly working IDE
Compared to what? Defining it inside a function?
ik
The benefit is having access to it from other functions
Right lets say i dont define it. Whats the actual difference?
What do you mean define?
Don't you mean assign?
Are you referring to the = new List<Item>(); part?
The difference between these two?
Hmm the difference is like resetting a list i think
Kind of
but by default i should always just define it in the global field right?
there literally no disadvantage
maybe performance?
Technically they are the same thing. The difference is that you assign a new list to the variable when you call CreateItemPool, whereas the other one will have the list assigned when your class is created
The only performance difference is when allocation happens to create the list. Nothing you should worry about
I think I get it when i do new its like list.Clear()
The thing with doing it through a method is that the list will be null for a period until the method is called
That's a key feature of reference types, like the list
Not really, clearing a list is better because you will still be using the same list instance. I am guessing that internally is just creates a new array which is less costly over assigning a whole new list
Again this boils down to allocation which should not matter to you
Direction = (source - target).normalized
thatll just make it go to the center
we want it to move away and it does at 0, 0 but not at any other cords
nope
Where do you want it to move?
From center to where?
we want to move it away from GoAgainst and to the edge of the screen
it doesnt work the projectiles just stay at a stand still
ima keep playing aroound with it
sorry for bothing you
Check the points. The direction must be equal to 0 if it doesn't move.
i found out smth that works
i just dk why
it looks the exact same as before
idk just glad it works now
Hi. I am new to unity and XR development. I am following this tutorial https://youtu.be/D8_vdJG0UZ8?si=0BX08V_WIMjsRU_k&t=378
In this video we are going to learn how to make your first Quest 3 XR game from scratch using Unity. This is the start of a tutorial series that will begin on this Youtube channel so feel free to subscribe to not miss the next one. :)
❤️ Support on Patreon : https://www.patreon.com/ValemVR
🔔 Subscribe for more Unity Tutorials : https://www.yout...
he is unfortunately using ver 57
seemingly the meta integration has changed. I am looking for some guidance to replace the OVRcamerarig
and the OVRControllerPReFab
assets
Can anyone direct me on this ?
You're better off asking in another channel, this channel is for coding questions. I doubt anybody would know the answer.
@burnt vapor like under platform?
Idk
hi again I need some help I have a script for a recoil in my fps game how to I make sure the script is running when I start the game?
should i attach it to the camera or player object?
That's up to you. Place it whenever it makes sense.
nothing happsn not even in the inspector
hi sorry if this is the wrong place to ask but i was wondering what the right way to create tests with the test runner when you are making use of coroutines and invoke? Also i have noticed that Start() doesnt seem to be called also
Perhaps i need to await something but im not sure exactly thanks
If you want a script to start when you start the game, all you need to do is attach it to a game object. I'm not sure if it must be an active gameobject or it can be disabled, but as long as you have it attached on an enabled gameobject its Awake and Start methods will play.
If you have all that, perhaps make sure you correctly named the methods, and you do not have any compiler errors.
it works now thanks
You can use WaitForSeconds inside a test with the [UnityTest] attribute and wait until the coroutine has finished: https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/reference-attribute-unitytest.html#play-mode-example
but that goes a bit against the idea of unit testing, ideally the code would be structured so that you can test the individual functionality of the coroutines without invoking them
ah ok thanks mate
i have a character with joints and it is rigged when i shoot it I want the body to splash any idea how i do that=? ;:D
To splash?
yeah or the body to become small cubes or particals
what every it could be anything I just want the object/character to change when i left click on it
Particle system?
yes can i script that or do i need something else?
You can create a particle system in the editor and then spawn or activate it from a script
okay thanks i need to youtube this 😄
What do you mean? Like "milliseconds"?
No, WaitForMilliseconds doesn't exist
I don't know why you'd need this, but maybe you were talking about WaitForEndOfFrame
Thanks
WaitForEndOfFrame is usually used for rendering related stuff, or when you want to wait for LateUpdate basically
Waiting for the next frame is done with yield return null for example
hi osmal! i have a VFX now but how do i called it with a script any idea?
i want to call the vfx when i hit the character with left mouse button
VFX Graph or ParticleSystem?
Either way, you just need a reference to it and call the Play method on it
is there a way to add the instance of a gameObject to a List<GameObject> and actually keep it there while changing the scenes?
The list is on the GameManager gameObject which has that DontDestroyOnLoad thing
Doing exactly what you described will work
Do note that the instance itself will still be destroyed unless it is also DDOL
so I am in a turn-based battle now... added the game object to the list with a bunch of additional check information... waiting for battle to end to see if it worked 😄
Sure, its up to you really
how do i check if a gameobject is on or not
sadly, it didn't
like if the check to enable or disable it is checked or not
Looks like it worked perfectly
if (!InGameMenuGameObject.activeSelf)
{
InGameMenuGameObject.SetActive(true);
}
else
{
InGameMenuGameObject.SetActive(false);
}
DDoL works on root gameobjects only, make sure they are
It's still in the list. You didn't read what I said.
"Missing" means it's a reference to an object which was destroyed
yeah... that's not quite what I would expect 😄 I hoped that the prefab itself will be kept in there as a prefab, you know... also I am sorry, I don't know what DDOL is?
Alternatively, activeInHierarchy if thats what is needed
It's not a prefab if it's in the scene
Prefabs only live in the project window
When you unload a scene all objects in it are destroyed m the fact that you have a reference to it somewhere doesn't change that.
If you want it kept alive, that's what DDOL is for
oh, okay... short question: Can I re-instantiate that gameObject from that list?
No
You have a reference to a destroyed object
If you actually referenced the prefab then sure
But this was an object in the scene
why doesnt this work
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenu;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Escape"))
{
if (pauseMenu.activeSelf == true)
{
Resume();
}
else
{
Pause();
}
}
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0;
}
public void Resume()
{
pauseMenu.SetActive(false);
Time.timeScale = 1;
}
}
The escape button doesn't work in the editor. Try a different key
Wait also you spelled it wrong
Just use KeyCode not a string
And you used ButtonDown instead of KeyDown
Many things wrong
Ok well that's fine then. Explain what you mean by "doesn't work"
like i press escape and nothing happens
what would be my approach if I would like to?
I am kinda trying to make that "pokemon capture" thingie and well, if I capture that pokemon in a turn-based battle... I kinda lose the whole information about it. Unless I want to make a whole big file with the whole lots of variable strings... and even then I am not sure I will be able to kinda do what is intended...
If this script is on a deactivated object it won't even run
the script is on my player object
Make a ScriptableObject for Pokemon information.
Make a MonoBehaviour for an active Pokemon in the game which references the ScriptableObject.
When you capture it, just save the ScriptableObject reference somewhere
Or a pokemon ID or something
I think you're in way over your head if you're trying to make Pokemon without first understanding some basics about object and reference management in Unity
And how to deal with save data for your game
learning now. I guess you would be quite surprised with where I am now 😄 for a beginner, offcourse...
so i added some debugs and i get every debug like i got the debug Paused
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenu;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Escape"))
{
Debug.Log("Escape pressed");
if (pauseMenu.activeSelf == true)
{
Resume();
Debug.Log("Resume");
}
else
{
Pause();
Debug.Log("Pause");
}
}
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0;
Debug.Log("Pauseed");
}
public void Resume()
{
pauseMenu.SetActive(false);
Time.timeScale = 1;
Debug.Log("Resumed");
}
}
try adding break; somewhere... because otherwise I guess due to it's Update, it does the thing 50 times a second
@amber spruce
There's no loop to break out from
hmm... oh okay... well... sorry for me being noob and trying to help )
Then it's working. What makes you think it isn't?
i got it to work i had to change some things but in the end it worked
1 question though when im paused if i move around like for example if i jump 10 times it makes me go super high in the air when i resume
disable the jump input if paused 🙂 not sure if it's how it's done, but that should work at least )
Sorry once again for noobish suggestions )
i generally disable the player movement behaviour when paused.
and reenable it when not paused
array is just a " list "
nothing complex there
techincally its a collection
whats there to get?
It's a variable that holds many things instead of one thing
it can be any type you want
Imagine a grocery list. You have [Eggs, Milk, Cheese] On the list. You cannot add anything to this list because you only have a piece of paper 3 lines big (immutable) You can access lists like this GroceryList[0] will get you "Eggs" GroceryList[1] will get you Milk. Etc...
Just read the message above it
it was basically what byte said
It was even a similar metaphor
I think we all learned lists from a grocery list example lol.
adding that's not mentioned yet, it's a collection of ordered elements of the same type
Fruit Array:
- Apple
- Orange
- Banana
An array is a list whose size can't be changed
Lists are different from arrays. But don't get too carried away with this.
Maybe Google the docs?
c# array
Hey yall, crazy question. I'm trying to print an exception caught by a try catch block using Debug.LogError. Anyone know how to convert the type exception to "object" (idk why its called this... but it is in the docs.)
why ?whats the use case ?
Overflowing a scoreboard. So the game doesn't crash.
just pass the Excepttion no?
wat
Error for type.
catch (Exception ex)
{
Debug.LogException(ex, this);
}```
ex.Message
Ah this!
Ohh you want the message
Wait nope
LogException does the same except it grabs it from the object
https://docs.unity3d.com/ScriptReference/Debug.LogException.html
Cannot convert string to unity object :(
Ah will give this a shot thanks
Show us what you wrote?
Debug.LogError(String.Format("Scoreboard Overflow! Digit Has gone over Scoreboard Limit! Error: {0}"),e.Message);```
for LogError you can just do ex.Message like SteveSmith mentioned
the second parameter is the object that called this debug
Little note:
If you have any scripts attached to any GameObject of the pauseMenu gameobject and those scripts have some logic such as obtaining settings data or doing some logic on the Start or Awake method it won't be executed since you're disabling your gameobject, what I usually do is putting a CanvasGroup component on the canvas and changing the alpha and interactable properties when i want to, example:
public class PauseMenu : MonoBehaviour
{
private CanvasGroup _canvasGroup;
private void Awake()
{
_canvasGroup = GetComponent<CanvasGroup>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Escape"))
{
if (!_canvasGroup.interactable)
{
Resume();
}
else
{
Pause();
}
}
}
public void Pause()
{
_canvasGroup.alpha = 1;
_canvasGroup.interactable = true;
Time.timeScale = 0;
}
public void Resume()
{
_canvasGroup.alpha = 0;
_canvasGroup.interactable = false;
Time.timeScale = 1;
}
}
The alpha variable changes the opacity of the canvas and the interactable variable changes whether the UI components inside the canvas are interactable or not
In your case it won't be really necessary to do this but when handling more and more things on the pause menu it will be worth it
Oh wait its not in the format!
yeah note the Object is the Unity class not the c# object one
Yeaa just missed my end parenthisis
why does it work like that, so that if my Unit <- base prefab doesn't work "MINE_VFX" entry in the Dictionary, but my Miner : Unit does, it still cannot get it from the dictionary, because it doesn't "see" it somehow?
Unit:
Miner:
and when doing
if (actionBasedPositions.TryGetValue(actionType, out var transform))
{
return transform.position;
}
return Vector3.zero;
it returns Vector3.zero because MINE_VFX is not present in the Dictionary in Unit
but it is on Miner
so why it doesn't work?
Debug.Log to see what actionType is coming in here
also it's unclear which dictionary you're looking at
public class UnitImportantPositions : MonoBehaviour
{
public Unit owner;
public GenericDictionary<ActionType, Transform> actionBasedPositions;
public Vector3 GetActionBasedPosition(ActionType actionType)
{
Debug.Log($"Action type: {actionType}");
if(owner is Miner)
{
Debug.Log("Owner is miner");
}
if (actionBasedPositions.TryGetValue(actionType, out var transform))
{
return transform.position;
}
return Vector3.zero;
}
}
so this is the entier class
i am calling this function on Miner, who inherits from Unit
Unit doesnt have MINE_VFX, but Miner does
and it just doesn't pass the TryGetValue, because Unit doesnt have it (but im calling it on Miner) and im confused
i'll post some debug logs screrenshots
print out all the keys/values in the dictionary
or use a debugger
to double check that the dict actionally contains that
is it becaues i have reference to the public Unit owner
and not the public Miner owner?
one sec
Could it be that the dictionary key mine vfx is coupled with vector 3 zero?
Is ActionType an enum?
yes
no because the second log is printing which is the "wasn't in the dictionary" thing
no
yes it doesnt SOMEHOW contain it
but it does in the inspector
and there is no way other unit is calling that method
you're probably looking at the wrong object
because there is only one unit at the scene
or are referencing the wrong object
i can print the owner name
one sec
hm.. it looks like it has prefab referenced instead of the actual object
because this is the actual object calling it
okay yea.. lmao
so i referenced the Unit inside the base Unit prefab
and then made a variant prefab from it called Miner
and i thought that it will somehow auto assign the Miner
instead it was referencing the old Unit (prefab?)
hey so im currently making a settings menu for my game and im trying to do resolutions and this is my code but when i play the game no resolutions show up
private void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionsIndex = 0;
for (int i = 0; 1 < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionsIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionsIndex;
resolutionDropdown.RefreshShownValue();
}
use debug log to figure out how many resolutions are in Screen.resolutions and how many options are there.
the length of it is 19
print out the options of your dropdown after adding it
yep that was the problem lol
i was following brakeys tutorial and must have thought it was a 1
fun fact, when you type for in your IDE you should be able to just press Tab twice and it makes the whole loop for you
sorry for pining, but the issue is still present, i actually think that is is related to unity somehow 🤷
Owner name prints "Unit" when it has Digger(Clone) (Miner) assigned - yes this is the same object, there is only one Unity in the scene
maybe use gameObject.name and see what that prints
that's what im doing
I mean the gameObject of the script
The fault could be in GenericDictionary 🤷♂️
Though I doubt it
But we haven't seen its code
the issue isn't related with the Dictioanry im pretty sure
the problem is that i ahve referenced the miner
but it does print something else
as a name
this is the Miner
when i click on the Owner it doesnt show the prefab in assets, but the object in hierarchy
then when I do Debug.Log($"Owner name {owner.gameObject.name}", owner.gameObject);
it logs "Unit"
instead of "Digger (Clone)"
and when clicking on that message, nothing highlights
What's the exact name of that object in the hierarchy?
That it highlights
You are talking about Digger (Clone) but in the inspector I see just Digger
Okay I see
yes becaues the screenshot is from prefab context
i will show you from game one second
when i click the message, it points to Unit prefab in asest files (not even Miner prefab)
Then something is maybe reassigning it
there is only ONE unit in the entire scene (this miner)
not possible
anyway, this is frmo game
and im printing the owner.gameObject.name
and it prints Unit and points to the Unit prefab
when clicking on that Owner
Maybe some serialization bug, try renaming owner to something else and reassigning it?
it highlights the one in the hierarchy
changed to unitOwner
let's see
same thing
nothing has changed
Owner name still prints Unit and points to a prefab
what the hell is happening
is this a Unity bug? @verbal dome
it looks like a bug with variant prefabs to be honest
because Miner is a variant prefab of Unit
when I am in the Unit prefab context, and clicking on the owner variable, it shows the one in the inspector
but when I am in the Miner prefab context, and clicking on the owner variable (not overrided), it shows Unit prefab in the assets
Prefab variants have had some bugs yeah
Not sure, try recreating the whole prefab variant
Or even the base prefab, at least to test it
If you can replicate it, report a bug
so apparently you cannot add new elements to the variant prefabs such as references, new list elements etc
becaues that just wont work and it will reference the Unit prefab
great..
It should work
i have made several test cases aswell
i know it should work
but it doesnt
2021.3.23f1 version
Also this is some info that you shouldve said in the beginning
I did
Alright
fcking awesome eh
Are you using [SerializeReference] anywhere?
no
actually the bug is more complex
the variant prefabs WORKS BUT they don't work when you have a variant prefab with different class assigned
so the Unit base prefab has Unit class
i created prefab variant out of it
removed the Unit class and added Miner : Unit class instead
and then it doesnt work
So it kinda still thinks that it has the Unit script on it
Well you just described it to me 😄
that is such a shame i can't even think of a workaround for this :/
Steps:
-Make prefab A with script X
-Make prefab variant B out of A
-Remove script X from B and add script Y which inherits from X
Right?
See if you can replicate it on a separate prefab
i need to somehow acces the Miner component
yes I can i tried that already
Then you found a bug, report it!
my first one 🥳
but anyway, do you think of a way of accesing the Miner component? :/
You could try using GetComponent to work around this bug, I guess
instead of the new added Miner
no because it points to a prefab
not to the instantiaated miner
when I do this
Debug.Log($"Owner name {unitOwner.gameObject.name}", unitOwner.gameObject);
from instantiated Miner
it points to Unit prefab
not the Miner instance
and the Unit prefab doesn't have the Miner cmoponent obviously
Yeah that's the bug, try a gameobject reference instead
Lemme know how it goes
if i wanna refefence the current script, do i use "this"?
well
same result :/
public GameObject unitOwner;
and then GetComponent<Unit>
is that what you meant?
let me try another way, creating a second variable
Yeah
and referening it only in the Miner
and leaving it empty in the Unit
nah it's the same
i think that just by referecing the variant prefab
it points to the base prefab
Iam trying to get a variable across scenes to show on text but it doesnt work
thank you anyway Osmal
Any errors in console when you play?
In what way does it "not work"?
nope
it doesnt assign the value
Is the code even running? Use Debug.Log
Also log what value is being set (killsText)
both PlayerPrefs.GetInt("kills").ToString() and killsText is in the console 0 for some reason
where do you Set
then that's your problem
is making the variable static better for variable transport?
hmm i barely use PP you might need to do PlayerPrefs.Save()
nothing to do with this code
no need to
why
because it's bad practice for beginners such as yourself who don't fully understand what the consequences are
I think it only gets called when application quits no ? which isn't called in editor ?
i could be wrong
unity saves preferences automatically on app quit
I hate playerprefs
yes
I never use it
binary saving > player prefs
as long as it's not pure json not encrypted
can you send me some explanation video or tutorial on binary saving?
you can google it
you basially get the array od bytes
encrypt it, save it into a file
then read the file, decrypt the content
I mean yeah , binary saving wont prevent any more protection than Json
that's true
less friendly for any prying eyes I suppose
yea, if the game is singleplayer it wont matter regardless
yup
I say let 'em
Stardew saves things in plaintext and it hasn't been a problem
rly?
need to take a look on my save file in stardew valley then
If people wanna push the game by messing with their saves, let em
they will anyway
cheat engine for instance
Yeah started saving things like Gravity in json just incase my players want to mess around
Yes, I've had to manually edit it before to un-stick myself when I accidentally installs a mod that changes the terrain slightly and my save is now stuck inside a mountain
but it is better to have a binary formatted saving when you will ever want to develop on consoles
binary just offers speed
if you have an object in do not destroy on load, does awake/start still get called if you change scenes?
No. Awake and Start run once.
The object is not re-created when you load a new scene.
If you want to do something when a scene loads, consider..
Those functions only run when the object is first created.
difference between Physics.OverlapSphere and Physics.CheckSphere?
OverlapSphere returns all of the colliders it finds. CheckSphere just returns a bool if it finds any colliders
so if you need the info about the colliders that are in the sphere, use OverlapSphere. if you don't need any info about what colliders are there and just care about whethere there are colliders there then just use CheckSphere
so for ground check it would be more ideal to use CheckSphere
i use a raycast
if you only care about if ground is there and not any info like the ground normal then yes
true i should switch to checksphere tbh for both wall and ground checks..
Be careful though, cause if you're doing anything with the player in terms of locking it to the ground, using a checksphere could cause your game to wig out some if it hits a wall or prop etc.
that sounds more like an issue of not using a layermask rather than an issue of just using checksphere
Yeah true, was just thinking of covering the bases. lol.
A raycast is more accurate than a sphere though, kind of by definition. It checks a single point instead of an area
Yeah I think pretty much everyone uses a raycast for a ground check tbh. At least in my limited experience (obviously assuming that's what you're doing)
i mean i worded it wrong, i just need it to be a sphere
for my type of movement
If you stand on top of a tiny hole then it thinks youre not grounded
why is it saying null checking is expensive
Hello, does C# not have properties like unity? I am trying learn about them but getttin an error.
Properties are a C# concept, not a unity one
Null checking a UnityEngine.Object is not exactly free (afaik it has to do soem checks on the native side) but it's really not bad
And sometimes unavoidable
But at no point have you ever been able to put them inside a function
It's a bit expensive. If you can avoid it by re-engineering your project it's usually a good idea to do so. Basically, is this null check there because itemData being null is a legitimate situation you are intentionally designing into the system or is it a band-aid for hiding an error that shouldn't be there in the first place?