#💻┃code-beginner
1 messages · Page 331 of 1
so when you do NOT press the keys, like not touching the keyboard, the player flies up?
uhhh ........ uhh
yepp
Simply using the GetKey(KeyCode) method
for mobile
i added a canvas with a slider, and it not appear on the gameplay screen, i new programmer, can anyone help me please?
so i use a button
either use an UI button or get the new input system and use the touches input.
tutorials can be found on google or learn.unity.com
check your scaling of your game view 😉
sry for my stupid question, but where can i check that?
its in your "game" window
should find it really quickly, as the game window isnt big
I don't think the UI Button has the events other than onClick. You, probably, gotta use the OnMouseDown / OnMouseUp methods.
Actually, you may want to implement your custom Button, which should be quite straightforward
this thing?
yea, what i should do?
debug log your moveDir
ok I'll try
Well, you have just shown the image with the slider in it
but when i run the game the slider dont apear
Then you may switch the scenes
Or disabling the slider
Please, show the slider on run time
the slider do not apear on the run time, thats the problem xD
Well, show its GameObject
Show it in the scene on run time
Using a UI Scrollbar, adjusted by the script, which has the stamina variable.
I see, would it take many hours?
Or is it a fast process?
Looking at something like this
In this unity tutorial, you'll learn how to make an energy/stamina system. Energy/stamina systems are efficient mechanics to increase player retention, pace content, monetize a game.
Timestamps:
0:00 Intro
0:16 Energy UI Setup
2:05 Energy Scripting
10:15 Conclusion
#Hooson #Unity3D
Play my first mobile game: Bot Attack - 2D Top-down shooter
➤...
-
- Create a
Scrollbar
- Create a
-
- Create a script for your
staminaif it's not created yet
- Create a script for your
-
- Add the
staminavariable
- Add the
-
- Add a reference to the
Scrollbar
- Add a reference to the
-
- Add a method to adjust the
Scrollbar'svalue
Takes 2 minutes for me, which is0.033if you need to know it in hours
- Add a method to adjust the
Could someone help me with adding a new inventory system to my project. i already made the new inventory system its just that i dont know how to add it properly.
I see, that's dope, how long you been coding for?
Not for too much. And I don't think it matters for your stamina scrollbar creation process
Might have a work opportunity for you if you are keen
what do you mean add it properly?
Show its distance to the camera
Exactly.
how i put it very very close
Does your canvas move with the camera?
yess
so i made my game (which already has a inventory system but its very bad) and then i made a inventory system thats good but i cant figure out how to implement it properly and some classes are overlapping and its confusing me very badly
I DID IT XD
thank you for your patience
I received this charge from just that Stamina Bar, and multiplayer server set-up, can't really fathom why.
Context: I was hiring a developer
The question wasn't referred to you, so I don't see why you reply to it. Also, this place is not for you to post it, and, please, consider not writing me dms about this too.
Okay no worries, just wanted a Game Developers POV, as I am afraid of being overcharged regarding this.
You'll have to show your current inventory system and provide a bit more context
Oh, alright, I'm sorry, I have not understood the question correctly.
So could you tell me time wise, how long this would take? Multiplayer and Stamina system set up?
I just wanted some insight haha
This depends on the level of the multiplayer.
It's just a lobby that's in a Pixel Game.
But stamina system, which is, if what you say, just a simply stamina bar, doesn't really require too much work, as mentioned above
Like a common server, like Habbo
Well, it really depends on the difficulty of the multiplayer
If it's hard enough, it could, probably, cost this much
I see, if it's something like Habbo, like a simple one where people just walk and interact via trading, would it be difficult?
I don't know Habbo.
I see, like a social Pixel game, I have the beta ready and I can share it with you here.
Can you enter into it? @willow scroll
What do you think?
only the old version or also the new version or both?
do you also need the classes?
Which one do you need to be adjusted properly?
my old one needs to go and the new one should be added but the classes then get all mixed up
Any thoughts on the beta multiplayer? regarding difficulty or complexity?
Well, just send what you've got now.
I'm not sure whether the game you sent is a multiplayer. The gameplay itself is not hard to implement at all, and is, as for me, very hard to understand (in terms of how to play the game).
As in, just a common server whereby you could see the players in the same lobby, is that difficult to implement?
It's still in the early stages so it is not playable yet.
Implementing a multiplayer is usually quite advanced, and I don't have much experience about it. Implementing this kind of server shouldn't be too hard.
I see, thanks a ton and appreciate your help here, really stressful for someone who hasn't really developed a game before to understand these timespans that are required for development tasks.
Well, I still don't see why you would hire a developer for this kind of game.
And I 1.2k is definitely too much for the simple lobby
I see, thanks man appreciate your honesty on this.
I hired because:
-
I have no experience in Dev work.
-
Takes time, have too many commitments right now.
-
Opportunity cost for me to pick up Dev, and start developing it myself isn't worth it at the moment.
Well, I honestly, don't think it's going to give you a profit this way...
But I'm not the one to judge 
Understandable, thanks for your insight on this.
How could I make a loading screen? Like a screen intermediary between 2 different screens where it says it's loading?
Two different scenes rather
So do you simply want to hear any suggestions on your code's improvement?
no i want to know how to implement the new one
i always get stuck bcs of variables that change and classes that overlap
Mm, I don't think I can give you a clear answer on this question
Simply name the variables the way that doesn't confuse you
And don't have a few different methods, all called Add or Remove
they are not confusing but the problem is for example in the old toolclass you dont have an enum but in the new one you do but then that doesnt work anymore
Load scene asynchronously. https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html
Use https://docs.unity3d.com/ScriptReference/AsyncOperation-progress.html for progress bar
"Doesn't work"?
ye it doesnt show up anymore even though i have the same code in a different project
and there it does work
Why would you have the same code in a different project?
its just a samplescene project for making the new inventory
I mean, I don't know how to help you, as this doesn't look like a specific issue
ok np
Is there a simple way to connect a float to a animation? I want an animation length for attacking to be the amount of attackSp. This attackSp will change often, so how would I go about making sure that the animation matches that attackSp length?
You could just make the animation loop and control the transition from your script with a trigger.
I tried that, but it isn't what my game needs. I need the attack animation length to be equal to the attackSp time (float)
why is my bool changing states from false to true when scenes are changed?
You'd have to show us what you mean
But, values don't change themselves
You might be getting confused by a different copy of the script existing in the new scene
@small mantle you can add a parameter to your animator controller with AttackSpeed or something similar, and in your attack state, use that parameter as a speed modifier.
so i have this game manager with this method that is used for a button to switch states, the bool isOn is checked by another script to wether do something or not public void toggleSpeech() { if (isOn) { isOn = false; } else { isOn = true; } }
Show the full script.
In a paste site
can u send a link for a paste site 😄
📃 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.
its a simple manager code just for a ui project
this is the script where isOn is checked https://gdl.space/wajiwuramu.cs
its at the last method
Ok so since this doesn't seem to be anything special, when you switch scenes You're going to have a totally different copy of the script
Everything in the old scene will be destroyed
right so i have to use dontdestroyonload?
right imma go learn that since i never have yet
ight
hello everyone , i have a gameobject and i want to create an animation where i move it around the scene ( i did it with the keyframes )
i wanted the animation to be relative to where the object is currently at
but it just always goes back the the position where i animated it in the window
any idea on how to do this
Animate it as a child of another object
A specific script has a maximal gameObject limit ? Bcs I want to activate a gameObject with SetActive(true) the condition works i test it with a debug.log but just Unity doesn't want to activate the GameObject
if (isAttacking == true)
{
if (spriteRenderer.flipX == false)
{
glowAttackEffectright.SetActive(true);
Debug.Log("glow right activate");
}
else
{
glowAttackEffectleft.SetActive(true);
}
}```
A specific script has a maximal gameObject limit
Not sure what that even means
i test it with a debug.log but just Unity doesn't want to activate the GameObject
What kind of test did you do? Did the log print?
If that log did print, add more logs to every place where you call SetActive.
YOu're probably deactivating the object elsewhre
It's a question
No i never put SetActive(false) in the code for the gameObject bcs i was thinking it's that too
Yeah but i'm not sure what the question means. Kind of like if you said "Does your dog have a maximal grocery store limit?"
Ok so... did your log print? Show the full script and your console window when running the game
Surely
I can't start OBS bcs my computer is.... bad but screenshot is enough ?
I just want to see a screenshot of the unity editor with the console window visible
and the full script
Why you lie to me
if(!isAttacking){
rightSide.SetActive(false);
leftSide.SetActive(false);
}```
That is really not the same gameObject
these gameObjects works perfectly
but the other idk why but not
OMG
I want to cry
bro you save me 💀
my mental health want to mercy you
I'm so dumb sorry to spend your time thx you
how would one go about checking if the collision on the capsule cast is at the top or at the bottom of the capsule (floor or ceiling, not walls) ? (because I want a different script to be checking for wall collision)
You can get the normal of the raycastHit and check the angle
Hello, the character is not jumping, please help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10f;
public float velocity = 100f;
private Rigidbody2D rb2;
public float jumpForce = 10f;
void Start()
{
rb2 = GetComponent<Rigidbody2D>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
transform.position += Vector3.right * horizontal * speed * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Jump();
}
}
void Jump()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.1f);
Debug.DrawRay(transform.position, -Vector2.up, Color.green, 0.1f);
if (hit.collider.CompareTag("Ground"))
{
rb2.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
Also check if the y value of the hit point is above or below the center
you are moving via the transform which is overriding any physics applied with AddForce
I didn't know you can get the hit point
one more question however, what if there's 2 hits one on the side and on the bottom for example
can I cycle between the objects that come in contact w the capsule?
Well, not all overrides give you the RaycastHit, so you would have to ise one of those
if so that would solve all my problems
It worked for me until I added a beam check
it shouldn't have
Each hit would be returned separately
great
move either via the transform or via physics. doing both is going to lead to issues.
and then once you've fixed that if it still doesn't work then you'll need to debug your raycast
You might even need to do CapsuleCastAll
Pretty sure that capsulecast, like raycast, just returns the first hit only
So using capsulecastall WOULD allow you to iterate the collider array it returns
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
transform.Translate (Vector3.right * horizontal * speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.UpArrow)) { Jump(); }
}
I need to optimize my hit detection cuz I use like 2 capsules and 4 raycasts to check for collision and that consumes a lot of resources for no reason, which is why I asked
you've changed nothing here
that is definitely not going to be a noticeable performance issue
What?
wdym what? transform.Translate is doing exactly what you were doing before
so nothing has meaningfully changed
That's almost literally nothing. Raycasts are basically free
What's different?
Similar
They appear to be literally identical
What are you expecting this to change?
well I also use portals that use cameras to render plenty of stuff at the same time so I try to save up where I can, also the collision system I got going on doesn't account for when the character stays still and objects move toward it so it just passes right through unless I press a key to move right b4 impact
The character can`t jumping
i've already told you why
You've been answered on what to do to fix that
Again, raycasts are basically free. If you're getting performance issues, it is almost 100% certainly something else causing it. If you hit performance issues, use the profiler to try to find out where and fix the things that actually have impact
proof for the "raycasts are basically free" claim: #💻┃code-beginner message
of course this was a test with no physics objects in the scene so i'm not sure if that would impact the performance. but doing 1000 took half a millisecond
about that what can others mean under CPU ussage?
also one last question, do events consume performance? like if I have an event going on every 0.1 seconds?
it's the work you do in the methods subscribed to the events that actually matter
void Jump()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.1f);
Debug.DrawRay(transform.position, -Vector2.up, Color.green, 0.1f);
if (hit.collider.CompareTag("Ground"))
{
rb2.velocity = Vector2.up * jumpForce;
}
are you still moving horizontally via the transform? because if so, you've ignored what i said
What?
do you know how to read?
I don`t understand this
what about that do you not understand?
This move either via the transform or via physics. doing both is going to lead to issues.
you need to move either by modifying the transform or by using physics. do not do both.
moving using transform.position or transform.Translate is obviously modifying the transform. using the rigidbody to add force or assign velocity is moving using physics.
how can i save a .txt file, that all players canm access?
so I have it setup in a way that I run an event every 0.1s using a timer, and when a certain object gets their start time = to the time broadcasted by the event, I use the DOTWEEN library to move said object, the timer resets when the player dies and the position of the objects do as well
I just want to make sure this isn't a bad approach or anything
again, any performance impact would come from what is subscribed to the event. not the event itself
thank you
This? ```cpp
Vector2 movement = new Vector2(horizontal * speed, rb2.velocity.y);
well that doesn't actually perform a move, but it's at least on the right track
You wouldn't use cloud save for that
just host a text file on your web server somewhere
Why not?
Cloud save is to save per-user save files
that are private to that user
it's not for "public" text files or whatever your use case seems to be
What kind of data are you trying to save here? A high score list or something?
I have like an app, where we track meetings, like the duration, date and members and stuff, and i need that stuff to be accessible from anywhere
why use a game engine for that? 🤔
Yeah what haha
Hello everyone...I am still new to unity and I am having an issue, the editor status show that I am getting 600FPS in the game menu...but VERY stuttering and unplayable...(despite it's being just a plane ground and a cube with an fps player)
Vector2 movement = new Vector2(horizontal * speed, rb2.position.y);
rb2.position = movement;
Your code is probably doing something wrong. like multiplying deltaTime into mouse input or something.
Just a small project for 6 people and i didnt want to learn anything new
well now you've made it worse. are you just guessing at what you should be doing? because if so, you should stop what you are doing and go learn the basics. there are some great courses pinned in this channel that will help you get started
well a game engine is for sure not the right technology for that
Vector2 movement = new Vector2(horizontal * speed, rb2.velocity.y);
rb2.velocity = movement;
my code you say?
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Transform MainCamera;
public float Sensitivity = 5.0f;
private float yaw;
private float pitch;
private float Xrotation;
public float speed = 1.0f;
private float horizontalInput;
private float forwardInput;
private float sprintInput;
void Start() {
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate(){
yaw += Input.GetAxisRaw("Mouse X") * Sensitivity;
pitch = Mathf.Clamp(pitch, -90f, 90f);
pitch -= Input.GetAxisRaw("Mouse Y") * Sensitivity;
transform.localRotation = Quaternion.Euler(0, yaw, 0);
MainCamera.localRotation = Quaternion.Euler(pitch, 0, 0);
}
void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * speed * forwardInput * Time.deltaTime);
transform.Translate(Vector3.right * speed * horizontalInput* Time.deltaTime);
}
} ```
"sorry"
you're doing your rotation in FixedUpdate
so of course it will look stuttery
Why are you using FixedUpdate
Worked for me so why spend the time to learn something else
well...thanks to youtube
what is the best practice then?
and you can get a screw into a wall using a hammer. that doesn't mean you should or that it is in any way the correct tool to use for the job
Update
with Time.deltaTime?
Sorry to disturbe you here, didnt thing anyone would get upset!
uhhhh oki
mouse input is framerate independent already. It doesn't need deltaTime
nobody is upset? it's just silly that you are trying to use a game engine for something a spreadsheet can do
WHAAAAAAAA
been stuck on this for 2 days!
man unity is not for me @-@
oh yeah...thanks for the help man
for now on...FixedUpdate is an enemy
mainly physics?
since I am working with a RigidBody for my player...should I put my physics in it without the Inputs?
If your player is using a Rigidbody then all of this needs to be rewritten
how come?
because it's completely ignoring the physics engine
and just teleporting your character around
it's not going to respect collisions and gravity etc properly
that's true...(this is what moving a player is all about)
like walls and props?
Why cant I edit the second Collider and how can I use it only as a trigger and not a collider
- Unity bug I guess, try restarting
- Check the Is Trigger box
In every Object I try to add 2 box collider, everytime the second doesnt display the button
Well you can still resize with the Center and Size properties in the inspector
but maybe because it's a prefab override
I can use this Button, kinda weird
When the 2. collider is checked at IsTrigger, it works like a normal box collider
Doubt
Oh, but it interacts with raycasts
yes
that's not "working like a normal box collider"
normal box colliders physically collide with other colliders
Raycast has this to ignore triggers if you want:
https://docs.unity3d.com/ScriptReference/QueryTriggerInteraction.html
but it's usually better to just put the collider on a different layer and use a layermask.
I mean, should it be between the predefined or can it be below UI
It doesn't matter at all
Ok perfect
Hello, does anyone know why my camera is not moving when I drag my mouse.
[SerializeField] private Camera cam;
private Vector3 dragOrigin;
private void Update(){
PanCamera();
}
private void PanCamera(){
if (Input.GetMouseButtonDown(0)){
dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0)){
Vector3 difference = dragOrigin - cam.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("origin " + dragOrigin + "newPosition " + cam.ScreenToWorldPoint(Input.mousePosition) + "= difference " + difference);
cam.transform.position += difference;
}
}```
what is it logging?
Also do you have any other scripts or components moving the camera (e.g. Cinamachine)?
Is it logging any difference?
Nope. And no, I am not using cinemachine
Looks like you;re trying to use ScreenToWorldPoint with a perspective camera
and you're not passing in a z distance
so you're just getting the camera's position out
you should probably use Plane.Raycast with ScreenPointToRay instead
Hoy all! Just trying to figure out here why a world object with a canvas attached using world space is being physically blocked by being visible by a UI Canvas using Screen Space - Overlay 
Changed to ortho. That did the trick. Thank you!
Overlay canvases draw on top of everything
Gotcha, so I need to use a Screen Space - Camera in this situation otherwise it'll always be blocking stuff - thanks! 😄
I have this asset that im using and I was wondering if I could get the thirdperson prefab and make it into first person would this be possible? https://assetstore.unity.com/packages/essentials/starter-assets-character-controllers-urp-267961
there is a first person template
yes but I want the third person prefab cause it has animations so I just want to change it to first person
Ah, well, anything is possible if you put the time into it
I have a script SoundsEmitter. It's attached to every object that emitts some kind of sound. This one is meant to be attached to the player:
using System;
using UnityEngine;
public class SoundsEmitter : MonoBehaviour
{
public int[] emittedAudio = new int[2];
public PlayerMovement playerMovement;
private void Update()
{
AudioChange();
}
private void AudioChange()
{
switch (playerMovement.state)
{
case PlayerMovement.PlayerStates.Standing:
emittedAudio[0] = (int)SoundsManager.SoundVolumes.Standing;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Standing;
break;
case PlayerMovement.PlayerStates.Walking:
emittedAudio[0] = (int)SoundsManager.SoundVolumes.Walking;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Walking;
break;
case PlayerMovement.PlayerStates.Running:
emittedAudio[0] = (int)SoundsManager.SoundVolumes.Running;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Running;
break;
}
}
}```
Now i also want to attach this script to a Bell which makes sound once interacted with, but I don't want to create a completely new script just to change 1 thing (removing the playerMovement variable in this case). Is it possible to edit this script without creating an entirely new one?
Hi guys,i am having a problem with an object,i want to make it rotate but it starts to rotate if i give him a lot of rotational force,how can i decrease it
the friction is set to 0
singleton audiomanager sounds like a solution
a low friction material and low rotational drag (angular) drag
I did it
It is like i have to give it so much rotational force
cause i tryed via script
so its better if i keep this script and define every sound emitting object inside of it? the problem is that this script has to be attached to the sound source, because i have an entity that checks all the gameobjects that have a SoundEmitter component.
drag = air resistance
angular drag = rotational resistence
Reverse the dependency. The player movement script should reference this one instead
They are both at 0
sounds good if its working
Yea but it doesn’t work
i'll try that. so do i do the AudioChange() method inside of the playerMovement?
I have 2 objects,1 rotates regularly and the other one not
whats that mean? play "spot the difference"
That method seems very specific to player movement
one must not be like the other.. and the reason behind differences
hmm, i think it will be better if i just create different scripts for all kinds of sound emitting objects.
It's really hard to say because the only part of this script you showed us seems very specific to player movement
How do i identify scripts with tags? I have multiple scripts that manage sound emitting, but each object has a different name of the script. for an example: player has a PlayerSoundEmitter script, while a bell has a BellSoundEmitter script. but these scripts all do the same thing: they manage sound, and each one of them has a emittedAudio[] float array. i can't attach a tag to the script, so how do i identify them?
if they all have different names why use tags?
can search for the component directly
I dont think u identify scripts with tags u would identify gameobjects with tags
scripts dont have tags
the only reason u'd use tags in that situation is if the scripts were named the same and u were trying to differientiate
If ur looking for a specific script you just look for those types
I cannot believe i forgot the syntax for this
FindObjectOfType
if they do the same thing, then why do they need to be separate scripts?
FindObjectOfType
Thank u lmao
in Unity6 its deprecated tho
yeah deprecated but still works
true.. just pointing it out
Also if each script has similar functionallity u should use a Interface
ive switched to FindFirst
IPlaySound
because i want to configure them differently depending on the type of the script. my PlayerSoundsEmitter script has a PlayerMovement playerMovement variable, but the BellSoundsEmitter won't need that variable.
i'll try using the interface
And you can just call there PlaySound Interface methods that way u dont have to worry about the specific script. If all ur really worried about is them playing a sound
again it's really hard to make recommendations here because the difference in what these scripts do seems really unclear
why not just have one soundemitter component that some other component drives? that way you don't have the same code in multiple classes
If all they're really doing is holding an audio clip and playing a sound when desired, it seems like this script doesn't do much more than what an AudioSource already does.
In that case you should delete the script entirely and just use AudioSource directly
these scripts aren't playing audio, it just defines the loudness of the sound it is generating. for an example: when the player state is PlayerStates.Standing the volume is 0, when it's PlayerStates.Walking the volume i 3 etc. it wont play audio, it just stores the volume and range of the audio. i have the volumes and ranges defined in enums:
public enum SoundVolumes
{
Standing = 0,
Walking = 3,
Running = 5
}
public enum SoundDistances
{
Standing = 0,
Walking = 10,
Running = 20
}```
Why can't your player movement script just do something like:
const float StandingVolume = 0;
const float WalkingVolume = 3;
// as needed
myAudioSource.volume = StandingVolume;
myAudioSource.volume = WalkingVolume;```
What does the script do when it's NOT being used for player movement
What does it do for a bell?
maybe sharing the code for this script would be a bit more illuminating
i didn't implement the bell yet, but the whole project i'm creating has a monster that reacts to sounds so it checks every gameobject with a script that manages the audio loudness, it checks the volume of all the scripts and checks which script has the loudest volume. then it sets the agent.setdestination() to the gameobject that has the script.
Then you just want a script like:
public class NoiseMaker : MonoBehavior {
public float volume;
public float range;
}```
Other scripts can set those values (the player script) and read them (the monster script)
it definitely shouldn't know or care about player movement concepts like walking/running/etc.
Ok. Thanks for the code, I will try implementing this later.
The bell script can be like:
[RequireComponent(typeof(NoiseMaker))]
public class Bell : MonoBehaviour {
public float BellVolume;
public float BellRange;
IEnumerator RingBell() {
GetComponent<NoiseMaker>().volume = BellVolume;
yield return new WaitForSeconds(5); // ring for 5 seconds
GetComponent<NoiseMaker>().volume = 0;
}
}```
should I worry about code efficiency in a 2D game
just as a simple example
Thanks for the examples praetor
Every game needs to worry about efficiency. But the specific things beginners worry about in terms of efficiency are usually not actually important. SO I don't recommend worrying too much about it until you have a performance problem.
Very fast typer
sure thing. These are quick and dirty examples which would need to be polished of course.
im a simple man..
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
AudioSource source;
private void Awake()
{
if(Instance == null) Instance = this;
else Destroy(this.gameObject);
source = GetComponent<AudioSource>();
}
public void PlayClip(AudioClip clip, float volume)
{
source.volume = volume;
source.clip = clip;
source.Stop();
source.Play();
}
}
i use singletons for all my audio (for the most part)
but i get that its not always the best way
so is singleton the name for static variables
singleton means only 1 exists
its a single instance of a class
Return after destroy here?
Oh alright
if Instance is assigned.. the class already exists elsewhere.. can just destroy this entire object
but.. i haven't figured out the best way to define a singleton just yet..
im working on it 😅 .. i have soo many different versions.. all a bit different
heres what i plan on adopting everywhere soon enough
actually u may be right.. i wonder if source will get a Null b4 it has a chance to get destroyed
i added one just incase 😄
Hm i doubt it, but not sure. Iir destroy is handled at end of frame, so GetComponent() should still be able to find something.
Ig in that case it wouldn't do much difference anyways, just for later down the road if you implement something like ddol etc.
using UnityEngine;
public class AudioManager : Singleton<AudioManager>
{
AudioSource source;
protected override void DoAwake()
{ source = GetComponent<AudioSource>(); }
}```
i went ahead and changed it over to use the generic singleton
ya, good catch tho.. can't hurt to be sure..
and from my understanding, i agree, Destroy happens at the end of the frame.. it gathers it all up.. and destroys it all at once
theres DestroyImmediate() but i think thats more for editor stuff
So I'm using rigidbodies for my enemies and player in my 2d platformer, and even if I tinker with the collision grid, they can push each other. Any way to prevent this? https://hatebin.com/wwftbgdakf
private void OnTriggerEnter(Collider other)
{
HandleExplosion();
}
protected virtual void HandleExplosion()
{
}
if something inherits this class, does ontriggerenter still happen and will handleexplosion fire?
As long as the inheriting class doesn't implement its own OnTriggerEnter
the -2 below the 0 should dissapear after a second but it doesn't, can anyone help me please? this code makes the text appear and dissapear
public IEnumerator ShowScoreAddText(int multiplier)
{
GameManager.scoreAddText.gameObject.SetActive(true);
GameManager.scoreAddText.SetText(multiplier > 0 ? $"+{scoreAddon}" : $"-{scoreAddon}");
yield return new WaitForSeconds(1f);
GameManager.scoreAddText.gameObject.SetActive(false);
}
What calls ShowScoreAddText?
void Update()
{
if (transform.position.y < -5)
{
if (GameManager.score <= scoreAddon) GameManager.score = 0;
else if (GameManager.score > scoreAddon) GameManager.score -= scoreAddon;
StartCoroutine(ShowScoreAddText(-1));
Destroy(gameObject);
}
transform.Translate(0, -speed / 100, 0);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("PlayerTop"))
{
GameManager.score += scoreAddon;
StartCoroutine(ShowScoreAddText(1));
Destroy(gameObject);
}
}```
You're destroying the object
the coroutine will stop when you do that
you can't run a coroutine on an object that has been destroyed.
shouldn't that happen after the coroutine ends?
why would it happen after the coroutine ends
it happens immediately
StartCoroutine(ShowScoreAddText(-1));
Destroy(gameObject);```
you start the coroutine
then you immediately destroy the object
should i destroy the object in the coroutine?
the whole point of the coroutine is that your code doesn't wait until it ends
sure, if you want it to happen at the end of the coroutine
thanks
calling a coroutine is like telling it to go ahead and run..
then the code moves along..
if(hitInfo.collider.gameObject.layer == 6)
Why does this line take so long to execute?
idk, it shouldn't.. really it would depend on the complexity of ur scene.. or hiearchy..
it could involve traversing through a significant number of GameObjects and/or components which could be where the delay is
The following code is stuttering, but the fps doesnt drop
if ur collision matrix is also configured in a way there are many layers with specific interactions it might also might make it where it has to do additional checks to determin the layer of the coliders gameobject
how did you come to conclusion its that line thats causing it?
if the fps doesn't drop.. its probably not a performance issue
in the following code, an object is moved to the position of the raycast, which only runs very slowly. If I change the code to e.g. false/true, the object is moved smoothly.
I'm really confused, because this doesnt require a lot of process power or a lot of data
It feels like a grid is created and the object can only be moved into the next cell
is it not your code? are u using a third party codebase or something?
No, just normal code
https://pastebin.com/yNCmtv8p This is the code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What does profile mean
look for big spikes.. when you come across one pause the game/profiler and select the spike..
you can go thru the heirarchy and find what in the code is causing issues
Ok, I try to search for the problem thx for your help
^ try restarting.. if that doesn't help its probably a loop
how would i make a collision between a box collider and a rigidbody work at fast speeds? my box collider is a moving platform but when i move it faster the rigidbody falls straight through
Continuous mode on collision for Rigidbody
i have tried that, still falls through...
you're likely not moving with physics
does moving a platform in the editor not effect physics?
not if you're moving the transform alone
ah
it will affect it but not accurate
right, and to effect it with physics i need to script that?
you need to move the Rigidbody itself with its own methods
like AddForce, Velocity etc.
i wanna explain what im trying to achieve, i have a platform that will be able to move to lauch the player, do i add a rigidbody to the platform so i can add force and just disable gravity on it?
if it only has to push player you can AddForce sure
you can also make it Kinematic and do MovePosition
sweet, thanks for the help!
Hi. I have a problem. I have bullet holes made by decal projector and if I shoot in the surface at a high angle the decal is stretching very much. How can I fix it?
protected void SpawnDecal(RaycastHit hit, Vector3 direction)
{
GameObject decal = decalsPool.Get();
float positionMultiplier = .1f;
Vector3 multipliedDirection = direction * positionMultiplier;
Vector3 spawnPosition = new Vector3(hit.point.x, hit.point.y, hit.point.z) -
new Vector3(multipliedDirection.x, multipliedDirection.y, multipliedDirection.z);
decal.transform.position = spawnPosition;
decal.transform.rotation = Quaternion.LookRotation(direction);
}
public override void Shoot()
{
animator.SetTrigger("Shoot");
audioSource.pitch = Random.Range(0.9f, 1.1f);
audioSource.PlayOneShot(weaponSO.shootSound);
fireEffect.Play();
if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out RaycastHit hit,
weaponSO.range))
{
SpawnDecal(hit, mainCamera.transform.forward);
}
}
you're displaying it at an angle of it being shot regardless of how sharp that angle is, so you could see what values you get from the "mainCamera.transform.forward" once the decals look off and simply clamp it below and above the undesired values
unless you want them to not stretch at all then I'm sure there is a simple way to just spawn decals with the default normal at a given contact point, but didn't ever use decals just deducting from the code
ya, just rotate it to match the hits' normal
decal.transform.rotation = Quaternion.LookRotation(hit.normal);
or -hit.normal
one of those two
or clamp it if you want some stretching up to a point
Also why new Vector3(hit.point.x, hit.point.y, hit.point.z) instead of just hit.point??
same with new Vector3(multipliedDirection.x, multipliedDirection.y, multipliedDirection.z);??
one does not question code that does the job
yes one does
Yes, it makes my left eye slightly bleed
I have no freaking clue what I'm looking at
could be worse... just put it in a function and forget about it 🙂
please, use a switch
i had a switch statement originally..
Thanks)
well its better than this
great idea! 😉
not sure about speed between the two, but nesting this much ternary operators is never gonna be more readable/maintanable than the switch. Sure, you saved 15 lines, but try changing anything in it, or getting to the bottom of a bug in the middle of it
your call, you might never have to go back to it, so enjoy it working and don't worry about it
ya, i havent checked the speed yet.. but my guess is its negligible
ya, i dont think imma ever have to modify it.. its just converting Cardinal directions to vectors
I see some examples of pattern matching for switch statements in C# posted on the web:
var operation = 2;
var result = operation switch
{
1 => "Case 1",
2 => "Case 2",
3 => "Case 3",
4 => "Case 4",
_ => "No case availabe"
};
Console.WriteLine(result);
didn't have the opportunity to try them tho. Might be nice for what you try to achieve
Good evening everyone! I started programming on Unity a little over a week ago, and I ran into what you might call a bug: when the character jumps, it moves in a direction not respecting the Vector3.up. I've been trying to figure out what causes it for days, but I've lost hope now. Here I attach the code. Thank you https://hastebin.com/share/uhomacexuv.csharp (If you see there's the function Jump() and MyInput(), i don't think the problem is in another position)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'd probably do this:
Dictionary<Direction, Vector3> dirMap = new() {
{Direction.North, Vector3.forward},
{Direction.West, Vector3.left},
// etc...
};
public Vector3 GetDir(Direction dir, Space space) {
Vector3 result = dirMap[dir];
if (space == Space.Local) {
result = transform.TransformDirection(result);
}
return result;
}```
ur epic
never used a dictionary yet
perfect timing
Is there a way to change the font (or force monospacing of the default font) of the Text Input box in the inspector?
The black screen is text mesh pro text
appears to be respecting it to me..
Vector3.up is global up.. it doesn't matter which way ur RB is rotated
transform.up is the local up
Yeah, i know this
well in the video its always moving up
If you see I'm going backwords
ohh, i thought ur issue was with the jump
Even if in the code is only mentioned vector3.up
btw dont do * Time.deltaTime; on mouse input
Mouse input is already Time Frame Independent
Your code is adding forces all over the place
void MovePlayer()
{
moveDirection = orientation.forward * y + orientation.right * x;
if (OnSlope() && !exitingSlope)
{
rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 10f, ForceMode.Force);
}
if (isGrounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
else if (!isGrounded)
{
rb.AddForce(moveDirection.normalized * moveSpeed * airMultiplier * 10f, ForceMode.Force);
}
}```
i know.. i seen that too
he's also setting rb.velocity in several places as well
ignoring the current momentum
Oh, i didn't know that. I use c# for site and html, so i'm a little confused in this moment
no worries just a unity quirk 🙂
but yeah also rb.velocity is overriding anything you do with AddForce
it'd be helpful not having to worry about the rigidbody rotating all over the place..
its for slope correction it seems though? should be fine maybe
most times people will rotate the player (root) gameobject on its lateral directions
and rotate a parented child Camera.. vertically
seperating the two rotations
that's literally what i did
then why is ur capsule leaning like its drunk?
it's funny to see
ahh, okie doke
how would i add an intiger to the UnlSkins in line 15?
OnSlope should probably be returning the corrected Velocity insted of being if statement.
just it, it doesn't have anything functional, but with or without the rotation the problem remain. It seems like there's a strange line that's messing up the movedirection
wdym by "add an integer"? are you expecting to resize the array to append the integer at the end? if so, use a List<int> instead of an array since arrays cannot be dynamically resized and you must allocate a new one to change the size of the stored array
but i don't have any idea where, this strange direction seems only picking the jumping from the ground (isGrounded) and not when the character is OnSlope or in Air
yeah I just use premade controllers 
yeah, i also tried with like the character controller, but i want to test like my ability from physics classes
yeah dealing with RB based controllers is tricky
yes, but it's fun asf
https://catlikecoding.com/unity/tutorials/movement/ you ever messed with this one?
when i will learn pretty well the part of movements i will give myself the permission to use premade code
Hello, I was wondering if yall know how to make it so i collide with something once it enables a gameobject, but if i collide with it again it enables a different game object?
int collisionCount;```
could do that with a boolean or a counter
and some if statements
Nono, i found some tutorials on youtube, but it's likme a mix with like 4 channels and some other things i made it by myself
yeah! this one was fun, was trying to make a Jet Set Radio clone with splines but Its in uhhh pause right now..
ya, i used this one heavily to learn how to code my character controller
lots of good stuff hidden away in that tutorial playlist
so, anyone have any idea of where this problem come from?
the only thing i can see.. is when u jump u set ur velocity directly..
thats going to cancel out any forces ur already applying to it
I should try adding a force?
theres an alternative..
pass its velocity back in to itself.. on the X and Z
and only change the Y for the jump
rb.velocity = new Vector3(rb.velocity.x, [yourcustomY], rb.velocity.z);
something like that ^
that way ur not setting em to 0
like u are now.
b/c as of now.. ur setting the X and Z to 0 when u jump
why is this if statement producing a NRE
protected override void OnTriggerEnter(Collider other)
{
print("BOOMERANG HIT SOMETHING: " + other.name);
if (other.TryGetComponent(out Character player) || other.transform.parent.TryGetComponent(out player))
but thats just (1) thing i noticed.. it probably isnt going to fix the main problem..
so, i fixed it
other.transform.parent is null
i just used an addForce
because it does not have a Character component or a parent
heck yea
and not change the velocity
shouldnt it just not complete the if
thank you so much and sorry, i'm noob asf and i thinki will kill myself ❤️
no worries.. we all had to learn too
if it doesn't have a Character, it will check the parent. At which case it will blow up if no parent
if it doesn't have a parent then calling TryGetComponent on the parent property will throw a NRE
i wouldnt go that far
Do this:
print("BOOMERANG HIT SOMETHING: " + other.name);
Character player = other.GetComponentInParent<Character>();
if (player != null) {
// the rest```
are there jobs in c#?
nope..
no like employment
of course
ima do smth like that when im older
thanks will try this
you should learn more than just c# tho..
ur best route is to know many different languages
gpt7 no more coders left /s
gpt8 no humans left
python, java, c#, cpp, c
jeez
im learning cpp and c atm.. b/c alot of electronics (microprocessors/controllers) use c and cpp
yes it does..
and verse
cool
but any Unreal i've done, its all been visual
you dont even have to touch cpp for most things in Unreal
its like a FPS generator.. everything has presets and wizards
i see
im just gonna try to get good a c# for now but thats something for in the future
thanks i appreciate it
How would i go about using an IsTrigger collider to detect anything with the "Enemy" layer selected? I know how to detect collision from specific layers in theory but it's never worked for me.
Not sure if this is more fit for #archived-code-general but i have hardly any idea what i'm doing and started 7 hours ago
use the method meant for triggers, and no this is not CodeGeneral topic
a quick google search should tell you which one you need
also you should configure you ide
ide?
the code editor
What exactly should i configure?
!ide follow the instructions here in bot message for VS
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
So just to check since the documentation is doing something a bit different, would this detect collisions from any gameobject with the "Enemy" tag and destroy itself if that happens?
not collisions, but trigger overlaps. otherwise yes. Also use CompareTag rather than string equality to check the tag of an object
the method is correct, the signature is wrong
oh wait, wrong paramter type lol
Which is the signature?
the parameters of a method
if you're looking at the documentation you will see which part on the method doesn't match
The documentation has this, unless I'm not seeing it, all it does is change the speed when it enters
you dont see the difference?
look at the paremeters of the method
you might wanna look again
Okay i can't say the word "O" for some reason, but my bad
Collider vs Collision
Yeah...
and another thing.. get in a habit of using .CompareTag("TagName");
its better than .tag
you need to get your !IDE configured 👇
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
u name the Collider other
u use that to compare..
not the type..
sooo.. it wouldnt be if(collision.. anymore
it'd be if(other...
I did all those things and nothing happened so i'm missing something in that
Sorry to be annoying everyone, I'm not normally i swear
close vs, try Regen project files inside external tools in unity page, then open script again
So like that?
☝️
and if that doesn't work then screenshot the entire visual studio window with the solution explorer visible
I don't think it worked
let it finish loading first
Where does it say it's loading?
well it doesn't show Miscellaneous Files or the Assembly-CSharp in the solution dropdown at the top so that indicates it hasn't finished loading
you also conveniently cut off the bottom of the window where you would see the loading icon
It looks.. different
yes because it is correctly configured now
I cut off the bottom cause it has info i don't want on discord
Sweet, now i have to figure out why the red squiggly lines are there, thanks for helping with that
because you spelled it wrong
and you terminated the statement with ; instead of ) to close the if statement
Thanks 😅
you can tell b/c of the Assembly-CSharp
now it knows its a C# script.. and will start highlighting errors in your syntax
and CompareTag
If i had more than one IsTrigger capsule collider on the same gameobject along with my script, would it detect them all as the "same" collider or would i have to specify something
Oh damn it destroyed the gameobject like it should.. That's sick
🤯 lol
Multiple colliders on one object form what is sometimes called a "Composite collider". They basically end up becoming one collider
Do you happen to have any docs on setting up rudimentary health values for enemies & the player? I haven't been able to find any but now that you've all helped me figure out how i'm going to do damage i think that's gonna help immensely
Not that i have any enemies with a navmesh agent yet
Okay thanks that's perfect
Hello 👋 I'm trying to set up URP and the Shader Graph.
When adding my URP Asset (with Universal Renderer) it breaks all of my textures (they turn magenta) and I get a missing reference exception camera error. Does anyone know what I might be doing wrong. For reference I am running 2022.3.13f1.
https://www.youtube.com/watch?v=YEk7mKovpUE&ab_channel=SpawnCampGames
i have this video
Oh that's perfect
it kinda has something about that.. I toggle a bool in another script ... but u can just as well change a variable..
or call a method that changes that variable..
and passing in a float or int
I would imagine i have to define different damage values from different attack types and then subtract that from the health pool
#archived-urp
but also "it breaks all of my textures (they turn magenta)" means you need to upgrade your materials to URP shaders
Thanks, I realized I posted this in the wrong channel. But also I’ve tried to upgrade them. It changed nothing. As well as creating new shaders and applying that to a new game object, there is no difference, it stays magenta.
then share screenshots of your materials in the correct channel and ask for help there
Alright, my apologies.
transform.Rotate
How would I go about playing a sound just before the destroy? Sorry if this is a very basic question
transform.RotateAround with the center point of the object
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
Use PlayClipAtPoint, which will spawn in an object with an audio source and then destroy it when the sound ends.
https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
This can be performance heavy if you do it a lot, in which case you would want to re-use the same audio source object and just update its position and play it again
Is the gameobject created as a child of the one with my custom script?
No, it just spawns an unaffiliated object whose sole responsibility is to play a sound effect and die
If it were a child objecti t'd be destroyed along with it and the sound would stop
It won't be Destroy(gameObject); for much longer
I'm tryign to implement health but it's confusing me a bit
Health & damage
the problem is that it treats one of the parts of the object as the center point
but when I use the rotate tool the center is the center of all the parts
lmao i like how the example code has [RequireComponent(typeof(AudioSource))] despite not using that required component at all
also thanks for reminding me this exists, i can add it to my feature suggestion of supporting AudioResource
Then use RotateAround and pass in the center of all the parts
I don't know the center of all parts
it's very confusing because when I click on one of the parts it shows up as 0 0 0 position
but the whole object is far away from that
how do I put the pivot somewhere else
What you see in the inspector is the local position
An object at 0,0,0 just means it's at the same position as its parent
What object do you have selected? Is your inspector in pivot or center mode
how do I switch the modes
Click the button on the top of the scene view
How should i start learning to make 2d games. I have literally no experience in coding. I once made a game in greenfoot :/
Pivot would be transform.Rotate
hi
im still stuck on this and i couldnt solve it
how can i know what unity is doiing while i am in this state , i litteraly can't debug anything because i have no clue what is going on
If this happens when you hit play, then you have an infinite loop somewhere
i removed every awake and start
What about Update
or OnEnable
hello
don't crosspost. your issue is not code related
Instead of blindly guessing, attach the debugger and see what's actually happening
If you really have no code running, then this is a bug
So, you have a completely blank scene with no objects whatsoever?
i'am strugling to install unity
there are objects on the scene
do you know how to read?
Not a code question. #💻┃unity-talk
And do any of them have scripts on them
yes they do
And do those scripts have functions that run at any point
but those scripts are useless because i dont let them execute anything
How do you prevent them from executing anything
Maybe show !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.
use the debugger instead of making assumptions about your code
i don't know how to use it ( never did )
after you attach the debugger click the break all button
I got it working, thanks guys!
player health does not need to be static
looks good 👍 besides the static variable.
u can also just remove the start and update(){} to make it a bit cleaner.. if ur not using them
I'm gonna probably use them later down in the line for updating the health and stamina bars but for now i think.. I might do some level design, y'know, the calm stuff
Hey I got a quick question with unity. I imported a sprite and sliced them to my liking but when i put it into the scene in the game view it does not show up does anyone know how i can fix this pls
make sure they are infront of the camera
also not a code question
its infront of the camera and where can i ask this question?
yea make sure the z position is bigger than the one on the camera
also #💻┃unity-talk next time
I have a kind of weird question, how would i influence an image in a canvas for something like a healthbar
I know i'd need to use void update(); to constantly refresh it but actually changing it is really confusing me
why would you use update to refresh it?
So it's constantly checking for whether the players health has changed
nahh , only change it when health goes down
no reason to be checking every frame that
So i'd add it to where it says PlayerHealth -= 20; just below
Okay that helps
yes, in time you do it via events etc..
transform.RotateAround(centerp.position, Vector3.forward, -45);
@polar acorn How do I make it not be instantly but rotate it at a certain speed
like make the rotate take 1/2 of a second
Hey I have a question, how do I convert mesh to a terrain and if possible convert 16 meshes into one terrain, or maybe if that's not possible convert it into terrain data and then attach the terrain component?
Call it multiple times with smaller numbers
over multiple frames
I know sort of how to reference scripts on the same gameobject so i could have a "Health Bar" script on the image gameobject, the "Player" script on the.. well, player and then use the player to change the "Health Bar" script which would change the actual health bar
Does that sound.. Right?
keep things simple for you have healthbar script be on the player
call method to update the bar only when your health changes
So put them on the same gameobject and then do something like this? myObject.GetComponent<MyScript>().MyFunction();
gameObject.GetComponent<Health Bar>().UpdateHealth();
[SerializeField] private HealthBar healthBar;
then drag n drop the object with HealthBar script inside the inspector field
boys and girls, we will start a study group where we will all share our goal at the start of the day and at the end of the day we will share what did we do that day. So if you are interested message me . Let's learn to codeeee! :yay:
Thanks a bunch, it's starting to look really cool lol
@rich adder If i want to update the Health Bar each time i take damage, how would i go about making HealthBar.UpdateHealth; actually mean something within the script? I'm assuming i need some int reference in the health bar script
pass in the PlayerHealth each time it updates
you would need to create the UpdateHealth method to take in whatever data type PlayerHealth is
How would i go about making UpdateHealth a method?
Or rather, do you have any good docs on making methods in general
Thanks
https://www.youtube.com/watch?v=_cCGBMmMOFw&list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw&ab_channel=SebastianLague
heres an all around good series to watch for beginners..
does anyone know the solution to this?
i watched it a few times when i first started.. near the end i was watching it on my 2nd monitor in the background while i worked with unity..
really helped me drill in the important parts and how methods work
Thanks, i'm incredibly new to this and probably annoying the hell out of people lmao. Should've watched a few hundred more tutorials
if u watch the first 3 or so episodes of the series i posted you'll have plenty of context to work with..
knowing terminology and what stuffs called helps tremendously when first starting
100%, when i was first getting into unity and people were helping me with modding it took 4 hours to figure out that the tabs had names and weren't just random places info was displayed 
like if i said.. you should pass in the health variable as a parameter to the function.. someone without a clue would be like "tf did u just call me?"
My mother was a saint
episode 4 walks you around the editor and tells u whats what.. Like "the inspector" "gameview" "Hierarchy" etc
but the 3 before it get u started with terminology of scripting.. and how variables and functions work together
Kinda feels like ep 1 kind of stuff
though I'm a year into unity and i still forget the names of tabs
So maybe not
lol.. well he starts u off learning what code looks like.
and then teaches about the editor.. and then goes str8 into coding a game
this is the best tutorial, I dont feel lost even though I have no idea about coding..
this first comment kinda sums up how i felt too..
im going on 3 years and i still don't know everything about the editor
and even less about everything code related
Okay damn maybe this is the best tutorial for real
The exact thing i'm doing 
mmhmm
Just a quick thing i haven't really looked into, is playerIsAlive = false; how i change the bool?
Also i know i'm getting annoying so probably last thing, if i want to play a particle system on the same gameobject how would i go about doing it?
just
gameObject.GetComponent<ParticleSystem>() ParticleSystem.Play();```
wdym how can you change the bool?
also IMO its bad habit to write if statement without {}
I just noticed i didn't have that lol, rectified.
it works but only for the line directly underneath it
What i mean is, since the bool is true by default, does the players health reaching 0 set it to false
do you know what = does ?
is equal to?
no
Oh is it double ==?
So if i wanted to asign it to be false i would use one =?
you want assignment, I'd say so
you may want to look at this closer..
if u want to destroy the gameobject if the conditional is true. u need to wrap them all in { }s
there ya go lol
So that would set the bool to false and destroy itself
in the code above that.. it would only set the bool to false..
and the destroy(gameobject) would run regardless.. b/c it wasn't in the brackets..
this only happens when the instance is created.
in Unity thats when you attach to a gameobject
or hit Reset on the script
if(bool == true){
CallMethod();
}
CallAnotherMethod();
``` is the same as
```cs
if(bool == true)
CallMethod();
CallAnotherMethod();
well you probably had no value before when you added it in the script
no value = default is assigned which in a bool case is false
you can omit the {}s.. but its only going to include the next line after it
anything else.. is considered outside the {}s
Kind of like that?
that last if statement is redundant..
no reason that i can think of to check that boolean at the bottom like that
b/c if it isn't giving the player damage.. it isn't gonna change the health.. and therefor.. he can't die
so only checking inside the ifenemy conditional would be good enuff
fun fact atm, the bool doesn't even matter.. b/c ur going to destroy the gameobject right after u set it to false..
If i did something like this where it's constantly checking if the bool is false and when it is, the player dies instead of having it in one if, would that be better or worse?
wait..
I removed the last if
why are you doing this
You should check when the player takes damage, not constantly every frame . . .
So i can flip the bool and have something other than the gameobject get deleted and so i can do it with other scripts
Wait, you already have that check. Why are you doing it twice?
Ignore the bottom one i forgot to delete it lol
My first suggestion stands. Check after updating the health . . .
Like this? 👀
I'm seeing more and more how completely redundant doing this is..
I think this is just better
also if you're destroying the object what is even the point of keeping the bool there
I'm going to replace it with a particle effect and disabling a few scripts then a respawn
Speaking of which, how do i disable specific scripts and play particles?
And respawn
"how to disable script in unity"
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
if (isAlive)
{
TakeDamage(damageAmount);
}
}
}
private void TakeDamage(int amount)
{
currentHealth -= amount;
UpdateUI();
if (currentHealth <= 0)
{
isAlive = false;
Debug.Log("Player has died!");
}
}```
heres a snippet from one of my basic controller scripts
if alive -> take damage
if damage is taken -> update ui
I found the answer for that but i've been hunting for the particles one for quite a while
And updateUI is a custom method on another script?
With actual functions in it
ya, or in this one
private void UpdateUI()
{
healthText.text = "Health: " + currentHealth.ToString();
}```
just updating a Text object
you create a TMPro element.. and then get a reference
And a reference is one of these? or is it a getcomponent and then modifying
public TMP_Text healthText; ``` or
```cs
[SerializedField] private TMP_Text healthText; ```
its either or..
they're both references... they're just assigned differently
the serialized field is better for me
you can assign a reference via the inspector. by using a public or a serialized field and drag it in yourself.
or you can assign it w/ code in a awake() or start() method
ideally you want to keep everything private unless you need specific reason for it to be public
its better to do it that way anyway..
a variable should only be public if it needs to be accessed outside the script for some reason
Isn't it [SerializeField] not serialized?
about 6 months.. but it is a character controller
there used to be dozens more
I'm still just using the base unity one with a different rigged model
playersActualSpeed is unused
i know.. it was for a speedometer i made for debugging
yeah i would def group them in their own structs, but yeah guess that could be too much abstraction for some :p
slowly getting it perfected 👍
spent 6 months or so building it.. and then 1 month or so refactoring.. and just last month i deleted about 25% of it
soo.. another refactor or so.. and it'd be package worthy haha
hey if it works it works lol
oh no, i totally agree.. it wasn't until this year i started getting comfortable using structs
structs, and the getter/setter properties.. took me a while to get a feel for
Oh not the axis, like pressing buttons
Vector3 !
although i'll have to remake moving it anyway so that's really useful
(0) (1) and (2)
GetMouseButton
..Down ..Up
but really these are easily googleable
So Input.GetMouseButton(0);
Sorry.. I should be doing that more i know
.. (0)
only so you get used to the result usually is for the api
look at the examples on the docs
Oh 
Thanks guys 😮💨
I'll stop bothering you all now, thanks so much for the help
its no bother just trying to get you towards the right way to do it :p
clicking these usually link to more info :p
I looked at the docs before hand and i have one more question
shoot
Does this mean it blends the current animation into a new one, or blend the one you want to play into another
I am finally setting up attacks
that one I dont know.. im guessing it blends the animation thats currently playing into the one u give the function ¯_(ツ)_/¯
could be wrong tho as I normally use parameters and set up transitions from clip to clip... just changing the parameters to let the animator handle the transitions
which function is this
wouldn't it be easier to just use blend tree?
ya, since ur beginner and everything is new to you.. it wouldnt hurt to jump right into blend tree's
much easier to do transitions with the graph than through code
Blend trees? Using the animator or is this code
animator
Oh i sort of know how to use that
Most of what i did was using an SDK so i haven't messed much with base unity stuff 😔
blendtree's look like this.. where u can modify that 1 single value.. and it'll blend between the 3 clips on the right
How did you get to that menu? Spam clicking the blend tree up here just sends me to the animator tab
you double click on the state for a blend tree in the graph, just like sub state machines, this is all done in the animator tab
newPassive.outline.OutlineColor = playerOutline.OutlineColor = GlobalValues.playerColors[ID - 1];
why does this line not produce errors?
how can i equal something equal something
this assigns GlobalValues.playerColors[ID - 1] to playerOutline.OutlineColor and then newPassive.outline.OutlineColor. it's perfectly valid to have mutliple assignments chained like that assuming you are wanting to assign the same oject to all of them
you're creating a chain of assigning the value to the right-hand side . . .
so they would all be equal to GlobalValues thing?
interesting
thanks
Hey, so i set up my enemy script to take 10hp whenever an is trigger collider with the RustedSword tag touches it (exact same method on player) yet it doesn't seem to work at all and i can't see any errors anywhere, anyone know where i might've gone wrogn?
This is player if it helps
do you have Rigidbody?
a collider with IsTrigger selected, actually have the tag RustedSword?
On which? the player or the enemy
one of the 2 things thats colliding with eachother
and the enemy
ok so you dont have a rigidbody
also this Collider shouldnt be IsTrigger most likely
for the enemy
The RB fixed it, thanks
It won't be forever, i'll end up only making enemy weapons actually hurt, the rest will be normal colliders
For now they're just static capsules lol
Have you ever messed with playing animations through script? I've been trying to get my attack anim to work but it constantly spits out an nre
its pretty easy to play animations, and if you have a NRE thats an issue with your setup of code/inspector and not animations
I don't see anything up with it :/
At least i'm not getting the NRE anymore
ah
Uh oh lol
are you holding mouse the entire time before and after you collide?
Where do you assign the animator?
No, i just press it but nothing happens
It is private and not [SerializeField] so theres no way its assigned
why are you playing the animation here even and why on mouse press?
and you get no NRE because the if statement doesnt run
unless you changed the code to assign anim after sending screenshot
Is that not how i should do an attack?

