#π»βcode-beginner
1 messages Β· Page 660 of 1
btw just a suggestion try to avoid magic numbers π
ye, I was just trying to prototype my structure for the rest of my game
oh and Start has a Coroutine version of the method btw
private IEnumerator Start() {
Can I make some parameters of a superclass to not show at all on a subclass?
Like the basic attack is child of the skill class, since it's easier to take as that for recounts and all, but I don't need it to have all these values, tbh
Those are only used for the other skills, and actually just for ease of display, they are not meant to be inpunt in there
Put [HideInInspector] line above the property in code.
Yeah, I WANT them to show for all skills currently, since I am currently testing that
But I don't want to show for that specfic subclass
Use a custom inspector . . .
How?
You need to create a custom inspector for that type (class) and manually draw the fields you want to display . . .
Why wouldnt you use those parameters. Seem like they should apply anyway
If you need to hide (unused) fields from a derived class, that's a code smell . . .
yeah, there are situations to hide stuff mostly enum related, but hiding parameters from the parent is odd
Actually half of those parameters are not even used on the basic attack
But it does basically everything else a skill does
So, I placed it under the skill superclass
Is like.... the most superbasic version of a skil you can have, and lacks a lot of the parts all other skills do have
Best way I would place a interface separating all other skills from the basic attack, but, ah, not really much worth it to work on that
It's mostly a convenience for me while moving through the components
I don't need a cd or cost for basic attacks, it's obviously 0 lol
sure but those being 0 are an explicit game design choice
so arguably they should be seen, no?
Those are meant to be shown on the description of the skills when chosing the given character, but a basic attack doesn't even show there, so it's redundant
One idea is abstract the top level and have a skill and attack derived class. Keep the behaviour in the abstract but make the derived fill out a struct of information to pass into the behaviour. Doing this will allow you to expose the variables in the child on the editor for the class that you want.
you ever just write something like this and start to wonder why english has different formatting for just 1 and 2
string ending = lastNumber switch
{
'1' => "st",
'2' => "nd",
_ => "th",
};
i never considered it before
i forgor rd π
return (new List<IDraggable>(ActiveLevel.Draggables) { ActiveCube });
Never used the param and constructor at the same time before, does this code correctly make a new list with the contents of ActiveLevel.Draggables and ActiveCube?
just sanity checking
Probably both???? I dunno
I would need to save a pretty good chunk of stuff, but also never done it before
I think I do have an idea of how to do it
there's multiple ways you can go about it
never save scriptable objects during runtime tho
instant regret
they're for static data
i use JSON for dynamic data
and player prefs for settings like audio graphics etc
if you have guns and items that appear or are equipped and unequipped then always have an index per weapon
then in your playerdata you save the current weaponIndex
you match it with the weaponIndex in your weapons.json file and bam you spawn it during runtime
thats my workflow
hope it helps
Ye, by the time I would be doing that I'll have 100% forgotten about what you just said lol, I still have a lot to go through first
But I have SEVERAL characters, each one with a bunch of values that need to be saved AND also, equipment for each one, so....
Convoluted
yea JSON it is
usually you want to build your save system alongside your game
otherwise if you have multiple scenes or a big project you'll lose a lot of time debugging
The idea is that the entities would be loaded from a prefab, you would have to check which entity prefabs the player has on the roster, then for each of them get stuff like the name and idenfiers for each of the equiped items. Eventually a system to save progress on the game like stages cleared or a common inventory should be needed
But all that is a issue for future me
Tsh, what a loser, that guy
is there an easy way to like, pause a gameobject? i need to temporaily disable two gameobjects and replace them with another, but i need them to keep all their variables and stuff, so i cant spawn new ones.
Specififcally, is there a way to turn of all updates, fixed updates, collision checks ect till another script calls it to "unpause"
Set the whole gameobject inactive (.SetActive) or disable individual components (.enabled)
Worth noting that OnTriggerEnter and OnCollisionEnter will still get called on disabled scripts
But not on inactive gameobjects
oh awesome, thanks! does this disable sprite renderers as well or does that needs to be done separately?
All of its components get disabled with the gameobject
thankyou!! ill go read the docs, that sounds great!
actually wait i lied im back, other scripts can still access the variables right? like the instantiated prefab can still read all the public variables for the script?
oh and adding on to that (but less important)
Can the public variables be set by other scripts?
Yes, the script component still exists in C#, it doesn't affect that
It just stops unity messages like Update getting called
thankyou so much for the help!!
private void Update()
{
moveInput = moveAction.ReadValue<float>();
if(jumpAction.IsPressed() && IsGrounded())
{
isJumping = true;
}
if(jumpAction.WasReleasedThisFrame())
{
isJumpCut = true;
}
}
private void FixedUpdate()
{
animator.SetBool(moveAnimation, MoveControl());
if (isJumping)
{
rb.linearVelocity = new Vector2(rb.linearVelocityX, jumpForce);
isJumping = false;
}
if (isJumpCut)
{
rb.linearVelocity = new Vector2(rb.linearVelocityX, rb.linearVelocityY * 0.5f);
isJumpCut = false;
}
}
is this good idea to divide jump like this? i know that rigidbody goes to fixedupdate? and i think register input should be in update ?
can anyobdy reccomend where should I learn c# from?
there are beginner courses pinned in this channel. i personally recommend starting with the microsoft one, then going for the pathways on the unity !learn site
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank youuu
Yes that is standard practice.
bet thanks, but when i hold the jump button, the max jump isnt consistent, dont know why
Your logic is likely causing the jump part to run multiple times sometimes, since there's no grounded check in FixedUpdate
And it's unclear how your grounded check works
like when i just hold jump, some jumps higher than previous ones, that can be from groundcheck? my groundcheck is a gameobject at foot with this: var hit = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
can it be frame register input stuff
make the cut sooner
I think it's what I mentioned and you should debug your code to find out
k i think thats radius 0.2f wonky sometimes
If I have a game object that starts on 0,0,0 for example, and I have a target, but I only want it to move 0.5 on the X and z axis towards the target, how would I achieve that?
assuming you mean you want it to move half a unit total toward the target only on the x and z axes and not half a unit on each of the axes, just get the direction (endPosition - startPosition), zero out the Y axis, then normalize that. after that just multiply the normalized vector by the desired distance (0.5 in this case) and that is the direction and distance to move the object (add it to current position to get desired position)
Oh true, sorry I meant half a unit on each of the axis. I'm basically trying to offset a position of a grid by half a grid width in both directions but specifically towards the target
note that half a unit on each axis is going to result in a greater distance than half a unit from the original position
anyway, if you want to add half a unit on each axis then you just need to . . . add half a unit on each axis
How would I know if it's +0.5 or -0.5 to make sure the end product is closer to the target? If that makes sense
get the direction and then just get the sign of each axis, it's just basic math
I see ty
If you guys don't know what i'm talking about my player capsule being missing on playtime, this video shows exactly that
Ok, i can't actually show the video
use mp4 to embed videos in discord
This is the issue i'm talking about
I'm using Linux Mint and the Linux version of Unity
this does not appear to be a code issue, but look in scene view, you'll see it is still there. what is happening is that your camera is likely inside the capsule which only renders from the outside. either that or your camera is simply too close to it to see.
I generally make my fps characters like this
okay, that does not change anything about what i just said
you should consider posting your issue in #π»βunity-talk or another relevant channel if you cannot figure it out using the information provided.
is there a particular recommendation for how to implement multiplayer? (as for the context of my use case: it's a turn-based board game)
it seems like there are several options, so I'm not sure which one would be the best for me
Hey, wasn't there a pluggin to preview the color of a hexocode inside the code with a small colored box?
It would be usefull now, I am using VS
probably, but that's not really a unity question. you can check the vs marketplace for extensions
Rider does it out of the box
im looking for doing the exact same thing
if you find a answer please tell me!
- look directly below their message for the correct channel to discuss networking in
- you are way too early in your journey to be considering any type of networking. game dev is already hard, making a multiplayer game increases that difficulty a lot
i want to save it so i dont have to scavenge for the answer, im grabbing the things i want to learn to then learn, just because someone is starting to learn art they arent prohibited of saving videos of perspective without even being able to draw a sphere, they can do it
i know gamedev is hard, im having trouble with a bug without it even being my fault, but you dont need to tell on my face that its too hard for me, i can look around
having a baseline understanding of the engine and your needs for the game is kind of a requirement to even understand the different networking options. it's pointless for you to seek recommendations if you don't even know what features you would need
as its a person that wants the same foundations as me i think it would be a lot more insightful than just later go blindly searching for the same question that they are asking
i didnt expected to join this server just to be greeted with being called uncapable in a pretty language
You're just being warned off from learning networking now. Not ever, and not because of "art".
Box is saying it now because 99.99999999999% of beginners who talk about MP and networking plan to do it now - you're not, you're just grabbing useful info for the future, so, this can all just be dropped.
Until you've made something that can at least be considered "a game", you should essentially assume multiplayer does not exist
i agree, i just feel it was a lot meaner than it could have been
also need you in unity talk
you may be having it told to you for the first time, our pov is saying it 039485u3049856430693i times a week
i can imagine that, it still hurts
Hello, I'm having an issue with my weapon switching system which is supposed to work side by side with my pickup script.
I can't switch to the other weapon on start (having the fists already enabled) as expected but when the pickup is picked up, I have to do a switch rotation twice before it actually appears and functions.
Like I get the weapon, I try to switch but all it does is disable the fists and doesn't show anything, then I have to switch back to the fists then back to the weapon for it to show.
I've been struggling with this issue for days and nothing on the internet could help me, I even tried with an AI but to no avail.
Same issue persists and I have no idea why, I was thinking it was because my weapon switching system has a variable that keeps track of the previous selected weapon so that you can't switch to the weapon that's already selected but now I'm starting to think it's not just that.
I've tried debugging with logs or forcing the script to activate the weapon twice on selection but nothing helps.
I'm relatively new to Unity and I mainly use tutorials to help me understand and work on my own and this kind of problem just stops me right in my development process.
Here's the weapon switching script and tell me if you also need any more scripts to help you understand, I can provide a video if needed.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSwitching : MonoBehaviour
{
[Header("References")]
[SerializeField] private Transform[] weapons;
[Header("Keys")]
[SerializeField] private KeyCode[] keys;
[Header("Settings")]
[SerializeField] private float switchTime;
[Header("Current Weapon")]
[SerializeField] private Gun currentWeapon;
private int selectedWeapon;
private float timeSinceLastSwitch;
private bool weapEquip = false;
private int previousSelectedWeapon;
private void Start()
{
SetWeapons();
Select(selectedWeapon);
timeSinceLastSwitch = 0f;
}
private void SetWeapons()
{
weapons = new Transform[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
weapons[i] = transform.GetChild(i);
}
if (keys == null) keys = new KeyCode[weapons.Length];
}
private void Update()
{
previousSelectedWeapon = selectedWeapon;
for (int i = 0; i < keys.Length; i++)
{
if (Input.GetKeyDown(keys[i]) && timeSinceLastSwitch >= switchTime)
selectedWeapon = i;
}
if (previousSelectedWeapon != selectedWeapon) Select(selectedWeapon);
timeSinceLastSwitch += Time.deltaTime;
WeaponEquipped();
}
private void Select(int weaponIndex)
{
for (int i = 0; i < weapons.Length; i++)
{
if (weapEquip == true)
{
weapons[i].gameObject.SetActive(i == weaponIndex);
Debug.Log("Trying to switch weapons...");
}
}
timeSinceLastSwitch = 0f;
OnWeaponSelected();
}
private void WeaponEquipped()
{
if (currentWeapon.GetComponent<Gun>().equipped == true)
{
weapEquip = true;
}
}
private void OnWeaponSelected()
{
print("Selected new weapon..");
}
}
When switching weapon, do you want to reset timeSinceLastSwitch back to 0?
if (Input.GetKeyDown(keys[i]) && timeSinceLastSwitch >= switchTime) {
selectedWeapon = i;
timeSinceLastSwitch = 0;
}
Oh, nevermind
You're doing that in Select()
Do you want weapEquip to be false again if .equipped == false?
if (currentWeapon.GetComponent<Gun>().equipped == true) {
weapEquip = true;
}
else {
weapEquip = false;
}
Yes but I'm not worried about that right now
this conditional is unnecessary, you can just do weapEquip = ....equipped;
(just fyi)
Yeah, I didn't want to say that yet lol π
oh this was adapted from their existing code, didn't notice mb
Yeah I know it's unnecessary but I wanted to make sure that it wasn't the equipped state causing trouble
I just forgot to remove it
new to the unity input system, how do i have combination inputs?
example: left click does something, but alt + left click does something else
cant find anything clear online
c# question: I would like to create a dictionary that maps an enum to different subclasses of a generic class, such that I can instantiate a new instance of the corresponding subclass (given only an enum value). Is this possible?
yip! ( thanks )
you can do it through reflection but I would just use pattern matching and do it in code which will be less indirect and more performant
ok, fair enough
Hey, I'm trying to make a top down 2d space game and I want to make a controllable ship with a grid that you can build on. like when you have a building selected it'll snap to a graph then you can place it if you have the requirements and the space. How would I go about making a ship using a tileset that moves, rotates, etc? or the grid eiter. I was thinking that you could make a prefab, tileset for the ship in the prefab. Then create box colliders etc. would this also apply for making modules to add to the ship
You could look into using Unity's Tilemap, as that can be updated in real time. Your spaceship could basically be a tile map with sprites and/or other gameobjects
Why is it that my decal projector looks like this in the scene view, but the second is in game view? I don't have angle fading enabled.
Thats a good idea, what would I do for the building system?
If you're looking to drag and drop pieces onto the ship's grid/tilemap, that's also do-able. There's ways to tell what grid cell the mouse is in, googling converting world or canvas coordinates to grid/tilemap coordinates will get you answers on that.
Your build menu would likely be its own separate grid and tilemap of pieces. You could do it also in canvas, but if you're already figuring out how to drag and drop sprites across grid/tilemap then why also figure out how to do it in canvas too.
Okay, thank you so much
https://paste.mod.gg/zhxwbnniszoj/0
What am I doing wrong with this object pool? When I run this code (the thing that calls the objectpool method is at the bottom of the paste), I get the error NullReferenceException: SerializedObject of SerializedProperty has been Disposed. I like to think its an error with the way the singleton is enforced, but I'm unsure
A tool for sharing your source code with the world!
hey there im brand new to making games especially on unity and im trying to make a bit of a first person shooter and have managed to get the play to move and jump with the inputactions and a charactercontroller and it works pretty well.. the issue im having is that if I transform the player to another position before run time my movement seems to be frozen.. I've even logged the position and it changes but the actual model doesnt.. sorry if this is not even the right discord channel for this and hopefully I could provide enough detail for someone to maybe understand what could be going wrong.. chatgpt also isnt helping lolol
Maybe I'm just not understanding the API correctly, but does OnColliderEnter2D also get triggered when an object/collider is instantiated already 'on top'/overlapping another collider? (One of them is a Trigger, the other has a Rigidbody2D)
Debug Log if the reference is null or not as I'm not entirely aware of that error.
And check in awake if it's being set
If they are instantiated on each other I don't believe OnEnter will be called. You can try OnStay instead, but I'm not 100% sure if the same condition applies
Nothing jumps out as wrong in the code, but wondering if you assigned a prefab in the Prefab spot or just a gameobject in your scene?
yup they've been added
objectpool and entitycontroller are attached to an empty gameobject
I mean in your list of pools. Are the gameobjects you assigned in there prefabs or just gameobjects in the current scene?
they're prefabs
I would think it's some load order problem but you are using start for the other mono. I'd check if the awake is called before you're acting with the pool
Huh, it works after I restart unity
This is so weird, is this a common occurence? I changed absolutely nothing
other than saving and restarting
classic.
I would change your ReturnToPool variable name from gameObject. That is going to be confusing/cause problems.
Yea you're right
I don't know. Something maybe hadn't saved like you thought until you manually did it. Hard to say.
Ah yes, the universal truth of computing. Restarting fixes most of your issues.
I still make sure it's not a load order issue because you may be getting lucky and it's having a race condition on loading
Ideally bump up the ordering in the settings, otherwise stick your singletons in a load scene to make sure they are loaded first then load your game scene
Oh yea that is a good idea! ty
Hey! So I tried making a gun which shoots projectiles but somehow the projectiles are waaaayyy too fast - any suggestions?
As in, moving too fast? Make the force less
Change the "force" field in the inspector
it works perfectly now! thanks yall!
it might be an idea to launch your projectile with a direct application of the desired velocity
yes, true but it works now so imma just leave it hahhahah
assuming the mass of the bullet is 1 then this will be equivalent to that. But yeah it makes more sense to just set the velocity so that doesn't change if you change the mass.
Anybody could help?
not likely in a #code channel
How can I unnatach a prefab on scene from the source prefab?
its called "unpack" in the context menu
so how do i even utilize the functions OnMove, OnLook and stuff
You just make functions with those names
And they'll get called when that button is pressed
does the script have to reference anything in particular?
No, that's what this component does
awesom
how do i make this simple function move the _characterController relative to the gameobject's Y rotation?
ChatGPT told me to change the last line to _characterController.Move(transform.TransformDirection(-moveDir)); which does work, but we all know how chatgpt tends to be so it might not be it
you mean the object's forward direction?
yeah
transform.forward will give you the direction the object is facing (its z)
yeah i just always forget what to do with that π
would it be any more effective than this? ( i do not trust the Chatter of the GPT with permenant solutions because its scary )
hello, I have coded before in other languages but C# is kinda new, i was wondering how to make the character object move while the mouse moves. I already got the basic wasd down, as well as the mouse input and the camera to turn in a 3rd person setup
but it wont turn the object so that the WASD changes direction
sorry if its a bad explanation
do you mean SD strafes as it looks at mouse
maybe idk what its called exactly
its a basic movement I just wanted to ask instead of pouring through docs and google
ill try explaining it more
basically, when I go forward, it goes one direction
and I want it to go whatever direction the mouse is pointing at
like if I start looking at one spot and turn the camera right
I want the object to turn that way too
ik its a really basic problem but I thought it would be faster to ask
Been a minute since I did a third person, but if you're treating i like FPS controls I think just grabbing the mouseX and rotating on the Y is all you need
add a "mouselook" script
yeah that or a lookat using the mouse raycasting for the direction
simple example: ```cs
public class CameraController : MonoBehaviour {
Vector2 rotation = Vector2.zero;
public float speed = 3;
void Update () {
rotation.y += Input.GetAxis ("Mouse X");
rotation.x += -Input.GetAxis ("Mouse Y");
transform.eulerAngles = (Vector2)rotation * speed;
}
}
rn I only have one script but once the game gets more complicated, I will add more and more scripts, do you want to see it?
I have it ready to paste
I basically have that just without the eulerAngles
instead its transform.rotate
there's different ways to do it
ill just paste the code script
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
private float speed = 0f;
private float TurnSpeed = 100f;
private float xRotation = 0f;
public float SensitivityX = 2f;
public float SensitivityY = 2f;
private Vector3 PlayerVelocityVar = Vector3.zero;
private Vector2 MoveInput = Vector2.zero;
private CharacterController playerController;
[SerializeField] private float playerSpeed = 3.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
PlayerVelocityVar = new Vector3(MoveInput.x, 0, MoveInput.y);
playerController.Move(PlayerVelocityVar * playerSpeed * Time.deltaTime);
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
xRotation += mouseX * SensitivityX;
transform.localEulerAngles = new Vector3(-mouseY * SensitivityY, xRotation, 0f);
float rotateX = mouseX * SensitivityX;
float rotateY = mouseY * SensitivityY;
transform.Rotate(rotateX, rotateY, 0);
}
public void OnFire(InputAction.CallbackContext context)
{
}
public void OnMove(InputAction.CallbackContext context)
{
MoveInput = context.ReadValue<Vector2>();
}
}
eulers is fine as long as you clamp it below 90 on the tilt
I dont really know what im doing, just messing around with the stuff
I had a 2 hour game development class today and am trying to practice afterwards
we had a bunch of problems before starting so that is all we got done really
Hey, after the new version of VS I lost like all the references to other scripts that showed on the top left corner. I was using that
Could it have lost a configuration on the update or something like that?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
What configuration? What you showed on the screenshot is the history of the last opened files afaik. And yeah, it can get reset on update or after regenerating project files.
Maybe take screenshot of the whole window, so that it is visible in context.
I assumed it would reset, but it has... reset like 3 times just today? And I am like... why?
I don't know what else do u want me to show lol
how do i make this input not also invoke OnJump() when releasing the Jump button
Hello
Someone directed me to this channel to ask for help
I keep getting this same error on all my new projects, I tried switching the version and that did nothing
Sorry for the bad picture, lmk if I should take another
(Or a screenshot lol)
No problem. Glad you're here, but since it's not a coding issue, ask in #π»βunity-talk
Ok
Thanks
Wait
Thats where the guy was telling me to come here
Whatever
Yikes. That is confusing . . .
AH, look, it did it again, I tabbed for a moment and I lost all the scripts I was working with!
Why????
π€· I'd just switch to another ide. If you're doing non-commercial work you can use Rider for free
using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
public class AstroidSpawner : MonoBehaviour
{ [SerializeField]private float timeSpawn;
public GameObject Asteroid;
private Vector3 Spawnpos;
private float SpawnOffsetX;
private float SpawnOffsetY;
private float SpawnOffsetZ;
[SerializeField] private List<GameObject> Prefabs = new List<GameObject>();
private GameObject PrefabAsteroid;
[SerializeField] Transform player;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
SpawnOffsetX = Random.Range(-10, 15);
SpawnOffsetY = Random.Range(10, 20);
SpawnOffsetZ = Random.Range(-20, 20);
Spawnpos = player.position + new Vector3(SpawnOffsetX, SpawnOffsetY, SpawnOffsetZ);
timeSpawn = timeSpawn + UnityEngine.Time.deltaTime;
if (timeSpawn >= 3f)
{
timeSpawn = 0;
AstreoidSpawner();
}
Destroy(PrefabAsteroid, 4);
}
void AstreoidSpawner(){
PrefabAsteroid = Instantiate(Asteroid,Spawnpos,player.rotation);
Prefabs.Add(PrefabAsteroid);
}
}
``` everytime i Instantiate the asteroid itll double each time, for example it starts at one then two four eight and it continues
You probably have this spawner script on another object as well, such as on the asteroid object you're spawning.
I had the script on the asteroid i was spawning and i moved it to an empty gameobject and it fixed it, why was it not working when i had it on the asteroid gameobject?
Because you're spawning an Asteroid, which itself has the same script, which in turn would cause it (and the one that spawned it) to each spawn their own Asteroid.
This process would continue, doubling each time.
oh okay! tysm
you can!?!?!?!?
i never knew this...
If I have a list A of objects with a parameter param, and a B list of parameters param; how do I check if every item on the list B is contained within the parameters of the list A?
Looping list B for each value on List A sounds like terribly slow
Make a subset of a list and share the reference between the two?
I think I would have to conver it back anyways, so wouldn't be much better???
Maybe I am wrong??
What is a "parameter param?" I'm lost . . .
Some arbitrary value I assume
Bro just wants to not do foreach value in list b does list a contain this value in list b
Not relevant to the problem what that data is I assume?
Is there only 1 occurrence of each value in your list A
UI is using a List of UI elements StatusInfoDisplayer; each of these has a referenced StatusEffect that is displaying, entities have a list of StatusEffect containing all the current status applied. I want to update the displayers in a way that each status on the list of the entity is showing in the displayers and removed when they are no longer there
They are instances of scripts so, yes?
Not sure why you need this whole list thing then
I would instantiate a prefab for each bit of ui for a single status effect
And organise them with layout groups
You can easily get something like minecraft style that way
Unless itβs actually important that certain status effects show up in a certain position on the screen or the like
That's... what I am doing? How do you do that without lists?
Like I need to hold how many stuff I need to show
Why does that need to be done in a list?
The whole idea of a class based structure is that each status effect could have a reference to its own prefab
You can grab that and instantiate it in some ui manager
Nope, it needs to be updated in runtime, they are not just prefabs
What each status shows is modified over time
They have a generic prefab for all of the statuses and what they display is modified on the instantiation and over time
Like you could have the same exact status but have now 3 stacks of it instead of 1
I need those references, is not isntantiate and forget
Sure so use listeners
Itβs better to distribute the job of changing the status effect uis to the status effect uis; results in much cleaner solution
When I say instantiate a prefab it doesnβt mean that itβs completely unchanging
Yeah, how do I keep a reference to it then without a list?
You donβt need to you can use listeners
Orrrr alternatively you have some list of status effects and the status effect ui bits can check vs that list themselves
That still solves the issue of needing this list comparison thing
I should probably use listeners, but seems like I am gonna mess up that and later I am gonna be totally unable to tell what is calling what
I would need to call the UI that may not even be active when ANY kind of status effect is applied or modified in any way and then check if it was applied over the selected entity, and then add it to the list of statuses, but they wouldn't even be updated to display the correct info giving how I am handling the intialization.... mmmm....
Definelty checking if something needs to be changed when a status is modified is more efficient that rebuilding it anew every X frames but.... I don't think I know how to handle that
I mean you can absolutely use a list if you find it simpler to implement
And when something occurs than needs ui to be changed you just iterate over the list until you find the correct bit of ui and tell it whatβs happened
And if there isnβt one you need to instantiate one
But idk where that list comparison thing fits into that
I guess I could actually use a dictionary???
Possible but holding duplicate data is unnecessary
I have A LOT of "duplicate" data tbh
Itβs ok to check on some class on the ui instead of having it directly correlated in a dictionary itβs not slow or anything
And removes any chance of mismatches or desyncing
The extra .001ms isnβt worth it
Couldn't each status instance just fetch their own status from a single source rather than a single source feeding it to each and every status instance? That way, if it's inactive, it's not fetching anything, and you could easily do culling to only fetch when necessary.
cant you have each of those elements in a list send a little message?
something like turning a bool to true
then when you want each specific element to do something you reference that one
that way you dont have to go through the list everytime searching for it
or an index
I ended using up a very convoluted system with a dictionary
I am seeing that I am gonna regret not using listeners in the future....
youre using a foreach tho
But I wouldn't even know where to start when doing that
Yeah. but not a foreach inside another foreach
At least I managed that lol
yea thats good
you can check for C# events
everytime theyre instantiated they send their individual index to a centralized list
then when whatever you want to happen happens
you reach that individual index and do whatever with it
ofc i dont know the full context of your code but something like this should work maybe?
this looks like a workaround of what im saying
from what im reading each statusDisplay gets instatianted
Why would I send the index??? You want to give the event an index value it should be affecting or....
yea exactly that
my point is instead of checking on each element if they have or not that status
each instantiated prefab would tell you already
Yeah, I guess I could make the isntantiated displayers check if the status is still running or have been modified, that's true
Not sure how much more efficient that would be tho
Joining late, are these ui views/elements that display a status all looking the same? (e.g. for poision and slow)
I would refresh the whole thing and just re display the current status effects, if it has too many views we just hide the un used ones or make more.
If it has a duration the UI view can countdown itself and hide itself but if we refresh it all then that ofc gets updated to the latest state
it'd make the code more independent, the instantiated display basically sends a C# event saying "yo the status is no longer running", here's my data to be removed
Statuses have a some parameters that are description parameters, things like name, icon, etc. Some do not change and are set in stone when created, other values can change and those are updated in the description parameters of the status when the UI claims for a refresh, once, refreshed they are pased to the UI to update to the new values
Things like icon or name can be read (config?) and shown on element refresh but these other reactive things I guess it depends on where the data comes from. This can also be read and used on a "Refresh"
That sounds like it's maybe better, I'd do that, but I have it working already and I not gonna redo it all rn lol
I can change it at any point anyways
Probably I will once I'm in need of those extra frames desperately, which surely is gonna be soon
Initialization sets the values of the fixed parameters, the rest are modified on a method that is called each X frames
If effects change this frequently then sounds like it does need to refresh quite often
why is my event not showing up in my player input events?
public void OnMove(InputValue value)
{
// Read input from the new Input System
movementInput = value.Get<float>();
}```
the script is on the same object, that's the functions showing under that script
if you are using the events rather than the send message option then your parameter is wrong
with unity events it needs to take InputAction.CallbackContext
InputValue is for send messages or broadcast messages.
for future reference, ask in #π±οΈβinput-system
question about events: it seems like invoking an event that isn't connected to anything causes a crash. Am I doing something wrong or is this just the way it is?
wdym by "causes a crash"?
an exception is not a crash. but if nothing has subscribed to the event and this is a pure c# event then it's just null, null check it when you go to invoke it. you can use the null conditional operator ?. for this
ah ok, thank you
I do this for my events: event?.Invoke()
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Any idea why I'm getting this error? ``` NullReferenceException: Object reference not set to an instance of an object
ProfileLevelDisplay.LoadProfile () (at Assets/Scripts/ProfileLevelDisplay.cs:25)
ProfileLevelDisplay.Start () (at Assets/Scripts/ProfileLevelDisplay.cs:15)
A tool for sharing your source code with the world!
I've been trying to fix it for a few days but end up breaking my game. I've tried asking AI before I asked here but to no avail.
usernameText.text = username;``` Seems pretty clear there's only one thing on this line that could be null
You simply haven't assigned the usernameText field in the inspector
this is one copy of the script
it is possible and likely you have another copy in the scene somewhere
type t: ProfileLevelDisplay into the hierarchy search bar to find it
actually
this isn't even the correct script at all
The script with the error is ProfileLevelDisplay so this screenshot is irrelevant
use this to find the issue.
Oh shoot, you're right. I've been looking at the wrong component.
This is the big error I've been breaking my game with.```NullReferenceException: Object reference not set to an instance of an object
DevelopersHub.RealtimeNetworking.Client.Sender.SendTCPData (DevelopersHub.RealtimeNetworking.Client.Packet _packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:14)
DevelopersHub.RealtimeNetworking.Client.Sender.TCP_Send (DevelopersHub.RealtimeNetworking.Client.Packet packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:39)
DevelopersHub.ClashOfWhatecer.Player.Start () (at Assets/Scripts/Player.cs:81)
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
I've also asked AI about this but AI's suggestions just break my game further
no idea what network framework this is but it looks to me like you're trying to send some network data without an active connection or client yet.
If you're a beginner i'd stay awaty from networking for now.
Hello, I hope I'm asking in the right place. Two of these errors pop up every time when I open a script. Even if it is a freshly created script in an entirely new project.
Been racking my head on this for some time now - google suggests launching UnityHub with Administrator privilleges for a similar issue but that does not seem to solve it. Any ideas? π₯²
those are warnings, not errors. but you need to go into the External Tools settings in your Project Settings and select your existing code editor as the script editor
!IDE π
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
Thanks @slender nymph, worked like a charm. Not sure if there is karma in this server π
this is normal for AI
don't use it
Am I misusing float here, or is some sort of AI misreading this variable's intent? One of the solutions is to make it readonly or to define a constant and assign its value to the variable - but not to assign the value to the variable directly.
What is the reasoning behind this? My goal is to just define a float variable in that script to use/adjust throughout the game.
misusing float
the message doesn't have anything to do with that though
to be clear, it isn't an error or a warning. it's just a suggestion that maybe you want to do that, but maybe not
in this case, it's because you never modify enemySpawnSpeed in the current state if of your code
a proper float would have a f behind the value
Damn, makes perfect sense! Thanks bunches.
but maybe you plan to do that in the future; in which case, you can just ignore the suggestion
a float literal, sure. it doesn't matter here though; it'd only be necessary if it weren't an integer
It's just a recommendation from your ide based on the fact you're never changing that variable outside the constructor
Yeah the IDEs really seeing three steps in the future nowadays! From a relative beginner anyhow. Thanks, peeps.
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What would be the best approach to have multiple resources able to be generated? I'm trying an approach with scriptableObjects, and the most, straight-forward thing would be to create multiple prefabs with a monobehaviour script containing the scriptableObject, but, isn't there a way to have a generic resource prefab that receives the mesh (or gameObject) of a resource from it's data and instantiates it on runtime?
You're sort of confusingly mixing a lot of terms here.
When you say a MB "containing" a ScriptableObject do you mean referring to it? What is meant by "resource prefab"? And instantiating the Mesh, or a GameObject with a MeshRenderer with that mesh?
The biggest question is what do you mean by generating resources
I have a pooling system with a damageable GO on my project, and when it gets destroyed I want it to generate (instantiate) resources.
Referring to the first question, yes, I was thinking of a resource class, a monobehaviour referring the resourceData scriptableObject.
My question refers to if there's a way to have an empty GO with that resource class and, with a factory system or event, it's meshRenderer and collider match the data resource with it's own GO.
If not, then i'll go for having multiple prefabs, each one with it's own resource class and data referring on it.
Multiple prefab is usually the way to do this
can somebody possibly help me understand why my Camera object is not being init properly? I have a main camera under XR origin, and the gyroscope/rotational perspective is working. but my Camera/Camera Manager are never being initialized and they throw errors for being null
Having a strange error with the unit 4 tutorial and was wondering if anyone could lend a hand, the if statement is supposed to active whenever all enemies are destroyed but it's not activating. Thank you
{
enemyCount = FindObjectsByType<Enemy>(FindObjectsSortMode.None).Length;
if(enemyCount == 0) // Respawns enemies if count is 0
{
waveNumber++; // Increase the variable waveNumber by 1 each time all enemys are destoried
SpawnEnemyWave (waveNumber);
numberDebug = true;
}
I have allowed camera permission on the device (Galaxy S10) and I included a permission script
you need to use three back ticks ( ` ) before and after the code block
Thank you
np. also you can enable language highlighting with ''' cpp (or other language names) on the first line
Can you verify that the Length == 0 when you expect it to ?
It is when I want it to spawn a new wave of enemies, I've narrowed down the issue further, something is adding to the enemy count when no enemy's are in the hierarchy
maybe make a log entry every time an enemy is created
And I've found it, the Enemy script has been put on the floor as well from when I was trying to drag drop the script!
Thank you for helping me debug this
It's a valuable skill
It really is. And itβs very frustrating sometimes but also very satisfying when you finally figure it out. Forces you to learn
I have a class that extends ICloneable. Does Clone work "as expected" for subclasses of this class? (i.e. instantiates an instance of the subclass when called)
or, must I override Clone in each subclass in order for it to behave this way?
maybe I should use my own method for cloning with a generic type? Β―_(γ)_/Β―
you could make a templated Clone
can you elaborate?
make a function that takes in type <T> and will return a reference to a new object of type <T> ? or just implement Clone in each of your types
I'm not super familiar with generic types, is there any way to constrain T to be the class I will be inheriting from (or a subclass of it)?
I will need to be able to access its class attributes
public void DoSomething<T>() where T : BaseClass```
like this, right?
This can be used to clone some of an object but it wont make a copy of a class ref for you
That seems much simpler
will a shallow copy work with Vector2Int attributes?
attribute as in the class I want to copy has something like Vector2Int pos

its not possible to have a reference to a struct without unsafe (or if we use a ref function arg)
unsure how to fit in MemberwiseClone here (where pieces is type Piece[,])
wait maybe this is not enough information, just to clarify I want something like r.pieces[x,y] = pieces[x,y].MemberwiseClone()
should work just fine if Piece is a class
the issue is that MemberwiseClone has a return type of object
if I cast to Piece, it will behave correctly for subclasses of Piece?
yes
no object slicing in C# is cool
Remember if Piece has some class ref inside that you also need to clone you need to do this process manually instead
e.g. a list
hmm ok, the other issue I'm seeing is "Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'PieceState'; the qualifier must be of type (class that I'm writing this method in)" on MemberwiseClone
oh, I think I see
(Piece)(pieces[x,y].MemberwiseClone())
use some brackets to make it happy or put the clone into a var firstly
nope, same error
it seems like calling MemberwiseClone always creates a clone of the class that it's written in(?)
based on examples I'm seeing online
wait nvm
its a member function you are confusing yourself π
Ah its protected so you need to add a function to PieceState that calls and returns the result
protected members can be accessed by the class and sub classes
public: everyone!
protected: only me and my kids
private: ONLY ME
yep
the main thing that confuses me is how class inheritance interacts with inherited methods :P
you will learn it with time
seems to work (for now), thanks for the help 
Does anyone know how to fix it by not getting the text deleted every time I type a letter and the front letter keeps deleting? I don't know if you understand what I'm saying, but I hope the video will make you understand
Press the Insert key on your keyboard, you are in replace mode
ohhh thank you!
I have some prefabs (that get instantiated, so I can't do it via the editor) and I want them to add a Listener to an Event of theirs inside Start(), but I keep getting this error instead.
protected override void Start()
{
base.Start();
hazardCollision.AddListener(GameObject.FindWithTag("Player"). GetComponent<PlayerCollision>().CollideHazard);
}```
And in PlayerCollision
public void CollideHazard(HazardType type, int score)
HazardType is an Enum.
I did pretty much the exact same in another game, and there it worked just fine, what am I missing here?
which line is 15 (the error line) for both of those scripts?
The one in Start() that actually tries to add the Listener.
hazardCollision.AddListener(...
This one.
most likely that GetComponent call is returning null
Did you check to ensure none of the references are null?
I got bamboozled by the space between the . and the GetComponent, I thought those were two different parameters
Nulls should not return the out of range exception, should return the null pointer exception, wouldn't they?
Out of range may be cause you are trying to pass an enum value that does not exist????
It says it's not in the expected range. That's a bit different from an actual out-of-range exception . . .
it could do anything - depends on how Unity wrote it
I believe either the "Player" is not found or it did not return the component from the player. I would also check the HazardType enum to make sure it's correct . . .
You should break that line into multiple statements for readability . . .
The error should give you the exact line to narrow down if it's the FindWithTag, GetComponent or AddListener . . .
The HazardType is correct. It's not finding the Component.
Ye, usually when you have a lwith multiple ".", meaning the get references inside references returning errors, you usually want to check each of the parts one at a time
When I do this kind of thing, I have the important components referenced from the main component, to avoid having to do go find them with GetComponent and others
okay so had a weird issue but figured out why it's happening, The X and Z value in this case '0' should remain untouched
so i need to somehow pass it the existing x and z value that the object drawer already has
you would get the current local rotation with drawer.transform.localRotation
Or rather
.localEulerAngles
since localRotation with give you a Quaternion
drawer.transform.DOLocalRotate(new Vector3(drawer.transform.localEulerAngles.x, openvalue, drawer.transform.localEulerAngles.z), 1f, RotateMode.Fast);
so something along these lines?
yes
though it would be slightly more efficient to use an intermediate variable here (or two)
How do you mean? Main component on what?
If you have a player type of script, and you KNOW you are gonna be calling the player collision over and over from different places, you may as well create a new variable on the player to slot the collision in, so you just need to get the player.collision instead of going throught the GetComponent, which is way slower and can also return issues that hard to see like the one you are having
That's what I do at least
I see, good point.
Yeah so, I realised i'm going to be using this script on alot of draws to open at all different rotations around the map so added in these variables for it to use, seems to work alot better
I think in this case the issue was actually something else entirely.
Because is it possible for GameObject.FindWithTag to find a child Gameobject with the tag first instead of their parent GO?
Because it wasn't finding any of my other components either, but by using GameObject.Find with the name, it works.
The lack of children that share the tag would also be the difference to that other game I did the exact same thing, where it did work just fine.
Probably would be better to us Vector3s
guys, if i want to write a default script that runs every update, should i attach it to an arbitrary object, or is there a way to create a scripting only object?
You must attach it to a GameObject in the scene for it to run.
you could write code that spawns such an object, if you wish, but it's pretty simple to just create the object in the scene
Shouldn't be the case
If you used ECS you could create those "scripting only" objects (they're called systems), but ECS is a completely separate and complicated beast, which it's not worth diving into for something this simple
Are you sure your parents does have the tag???
well i want to write a script that will populate the scene at runtime
maybe attach to the camera I guess?
make an empty object in the scene for it
don't put it on the camera
okay
It does. And it's the only top-level GO in the scene that does.
Usually, stuff that happens on an overall level is commonly attached to a "GameManager" empty object and a script of the same name
Thanks for this. I have just created it as ScriptManager. ill rename it
Should return the first one, and I think children should be after the after on the search
Apparently it doesn't. I just checked, and just doing FindWithTag randomly gets me one of the turtle's flippers instead of the main body.
Not 'random', apparently arbitrary, but consistently.
Yeah, probably solvable, but I would just advise you to make the player a singleton, so you can inmediatly get it without any tag to search for
Not sure if the issue is in code so i'm gonna put whats happening here because it probably is,
This draw is being specifically weird, this is it's default rotation
-180,0,0
So i set it's closed values
this is it's open value
rather than hardcoding it you could just save it in a variable in Start()
I could to that yeah
but yeah when I open this door
it flips on it's head
and I have no idea how or why because i'm just changing the y value
well for one, your scale is -1, -1, -1
what's that about
It just seems to be how this model came
well it's going to mess with all kinds of calculations
Oh, i'll copy and flip the other door and try and see if that helps
so, one fun thing about euler angles - they're all interdependent. If you're rotating on more than one axis, it's sometimes hard to predict what will happen when you change an individual axis.
Yeah i can't copy the other door it's not modeled to allow that
with the handle placement
Why not just animate it instead of hardcoding it?
I'm liking learning how to tween π
plus from reading, animating lots of simple things like opening a draw is somewhat overkill
Oh so the -1 isn't the issue, the doors below also have -1 on scale and they work fine
basically it's going to be easier if you start off with sane values for things. Like a scale of 1, 1, 1 and a 0,0,0 local rotation
If you need to rearrange the hierarchy a little bit to achieve that, it may be worth it
and my script seems to work fine on those
I'm just wondering why it would be any different on the top
I must have overlooked something
Fixed, a default position was set to -180 instead of 180, not really sure how or why but all good now
Problem π€. I want to make a 2D monster appear to spawn by starting its y scale at 0 and animating it to 1. However if I spawn it at normal size, it flashes in full glory before starting the animation. Meanwhile if I start it squashed - it goes back to being a pancake after finishing 'spawning'.
Is there some obvious solution to this I am missing? Perhaps a way for animations to alter the parameters permanently? Or spawn it already playing the animation? I realize I could alter the scale in accordance to the animation separately, but that feels like a really backwards solution.
Sounds like this would be a common problem. I would think there's a way to just start the animation at a specific frame on the API
otherwise script a way for it to not render until a frame has passed
That might be the way - having the prefab squashed by default feels even more backwards. Thanks!
All I could come up for this late at night was that a 2D sprite is already a pancake. Squashing it flat height-wise rather makes it a french fry.
I'm trying to add object pooling for a bullet (dissapates after a time), but I think the code is a mess. Can someone please give me some tips so I don't lose my mind when I am looking at this stuff in the future? If I were to access the animator here, to set the fireball to detonate after hitting the enemy or exploding after n seconds, would I put that in the Fireball class? What is the "proper" way of doing this? Cuz this looks horrible
`public class Fireball : MonoBehaviour, IPooledObject
{
private float travelTime = 1f;
private float velocity = 15f;
private bool isTriggered = false;
public void OnSpawn()
{
}
public IEnumerator projectileSpawn(Vector2 unitDirection, float ChargeTime = 1f)
{
float StartTime = Time.time;
while (Time.time < StartTime + travelTime && !isTriggered)
{
transform.position += (Time.deltaTime * velocity) * (Vector3)unitDirection * Mathf.Clamp(ChargeTime*0.75f, 1, 5);
yield return null;
}
}
}
IEnumerator FireballCoroutine()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(new Vector2(Mouse.current.position.x.ReadValue(), Mouse.current.position.y.ReadValue()));
Vector2 playerPosition = transform.position;
Vector2 direction = (mousePosition - playerPosition).normalized;
GameObject fireball = ObjectPool.Instance.SpawnFromPool("fireball", transform.position + (Vector3)direction, Quaternion.identity);
IPooledObject temp = fireball.GetComponent<IPooledObject>();
yield return temp.projectileSpawn(direction, 1);
fireball.SetActive(false);
ObjectPool.Instance.ReturnToPool("fireball", fireball);
}`
I'd ditch the coroutine and just make an update in your fireball class
Also just wanna point out that's an unsafe getcomponent
Probably fine in how your using it but easy enough to avoid so
Sorry could you explain? im new
so when you get IPooledObject from fireball, your not checking if that is null or not
so if IPooledObject wasn't on it the code would error
Oh I see
On the topic of components, If I have an object in my object pool being reused, and if I make a component call like GetComponent<Animator>(), would I have to make that call again when it's made active again?
So would this issue only come up if I ever disable components? (I'm not sure how it comes up null)
it's good practice to just always check, Unity provides a TryGetComponent function that makes this easy, so eg., you could do
if (fireball.TryGetComponent(out IPooledObject temp))
//stuff with temp
else
//yield return null or something similar
Not experienced with pooling so can't help too much with your other questions personally, sorry!
in this case it's probably a fine assumption to make yeah but just getting in the practice of always checking before using stuff is a good habit
will do!
also somewhat nitpicky but if it was enabled it would still return the component. being enabled/disabled is a unity specific thing applied to things deriving from Component/MonoBehaviour but null is a concept c# introduces
oh ya
im unsure if this is an issue with my code or with how i've set up my inputs
the issue is, is that it seems to jump twice when i press the jump key, and then jumps again once i let go ( when im grounded, ofc ) ( look at the log as the video plays )
in the video i just hold the jump key and then let go once i hit the ground
i want to make it not do the weird double jump thing, and also not activate when i let go of the key
Ideally you want to add some cooldown on the jump, maybe a few miliseconds or two as your collider may still be touching the ground before you're considered non-grounded
For the button release problem, I'm a little rusty on that input system but you need to specify somewhere to trigger only on press
Try this in your statement there:
if (ctxt.performed && _isGrounded)```
what does ctxt.performed specifically do?
You aren't manually subscribing to the events because you're doing it in the UI, so basically you're getting callbacks for every action. So you need to specifically figure what callback you're getting.
Hey, can I have like... I way to like... totally replace an object from another?
I have kinda of a complex UI element that changes on each scene, but it's inside of an UI that is persistent throught scenes, so the ideal would be having a prebuilt one, that replaces the old one on scene load
ooohhhh, that might also be why its doing the input twice aswell maybe?
You're getting both started and performed callbacks probably, but you only need one of those. If not performed then try started
alright, yeagh, adding that fixed both problems, thanks! :3
Idk what i did, i followed what the tutorial said
What is postion
!ide so you don't make spelling mistakes in the future
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
idk, i used an offical unity tutorial
So where'd you get postion from
honestly, idk
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 186
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-05-16
Yes
dang...
Do this
ima give you an update tommorow bc its 12am for me
Is anyone able to explain to me what is the highlighted line actually doing? I am trying to understand this thingie cause seems useful lol
few operations that could otherwise been an extra line or two but the devs love saving line space
it's reflection.
field is a FieldInfo corresponding to the field named [value of key] in TextFormatting
presumably it's a static field because GetValue seems to take an instance
then it checks if the value is null; if it isn't, it continues the chain, calling ToString(). if it is, it short-circuits as null, which gets picked up by the null-coalescing ?? and givesmatch.Value instead
So I can just remove all the "?" checks, cause that's a static method that is always there and filled with values
i suppose, yeah
Is this right then?
but imo this would be cleaner with a map if possible
A map?
no, this stringifies the fieldinfo instead of its content
a Dictionary in c# terms
So this?
I was using a static class that just holds references to colors and icons I am using for texts, so if change any, they change all automatically, but now I need to do that from a textInput in editor to save some prefabs, so I cannot just interpolate the string to call those values from there, how should I handle this then?
This is the reason ScriptableObjects exists
with a dict you would have a similar setup, it'd just be storing and accessing the values differently
Wouldn't I get the exact same issue of not being able to interpolate any value of a SO on the input text?
Basically I save the coincidences of strings I want to look for as keys and do the same replace by the value of each of them which would be the reference to the TextFormating right?
I think you are confusing the term interpolate here. You want to read a color value and use it in the editor correct ?
Presumably you are making some sort of UI theming system
wdym "coincidences"?
Basically I want to be able to do this kind of formating but to work on editor
Well, not on editor, but the string that I pass in the editor to do an "interpret pass" so it gets the right values before passing it to the TextMeshPro
so poor man's interpolation basically
I guess I am a poor man, yes
lmao i didn't mean it like that
it just means a recreation of the feature when the actual language feature isn't available
so what did you mean by this? im not sure what you're referring to here
I want to check for stuff like {healthColor} on the text, and translate that to the value of the healthColor on the TextFormating, so I am guessing what you mean I do a dictionary where {healthColor} is a key and the value is the value of the textFromating.healthColor and do the same replacement there
right
also with this if you use a serialized dictionary you could modify it from the editor without having to recompile
I would... have to copy each of the values manually on the editor whenever I change them then....
wdym by that?
you'd still use a single source of truth, it'd just be in a different place
If I decide I no longer want [armorColor = "<color=#FFFF00>";], if I serialize the dictionary I would have to change the value there too, not only in text formating
same thing with the static fields though?
I am saying I would have both, not that the static wouldn't need to be changed lol
why'd you have both though
see above
ngl the suggestion i posted yesterday kinda seems like it does all this, aside from additionally defining how to encompass a specific region of text inside the string via an arbitrary interpretation sign
Cause getting the references would be harder from a dictionary than from a simple standalone parameter
Which one?
the scriptableobject dictionary one
not sure what you're talking about, the dict would be basically a singleton or maybe on an SO (i don't really know how SOs work. i should look onto that)
But like, how is this better with a scripteable object??
you'd probably have it on an SO thats refed by a singleton
you don't have to recompile to make changes
why not just have the dict on the singleton though, at that point
moving the definitions from explicit code to serialized editor inspection is better for iteration and intended unity workflow
I mean you could but you could say that about a good amount of SO usage π , just depends on personal limits and preferences
For something that I am gonna change with relative frequency, sure, not for the freaking text style lol, that can be hardcoded
It's fine
gotcha
if you want idk
formatting seems like something you'd really want to be able to iterate easily 
I am gonna format based on the TextFormating class, but that class is not gonna be changed, it's just, basically a SO already, it does nothing but to store values
i mean, you gave a concern/example yourself lol
not directly a critiscm or anything but you come in here asking about the best way to do things a lot and a majority of times you prefer doing not the best way to suit your pre-established preferences. This isn't a problem in itself or anything but it might be worth considering that approaching the question with the intent to find the best solution might not be the most productive way to illicit the answers your looking for
Can I pass the value of a scripteable object parameter to a field on the editor?
it's a Object so ye
the same way you did here lol, with reflection
but a dictionary would generally still be better DX (and to lesser importance, better perf) than reflection
and even better if you serialize it
making good, scalable, flexible systems isn't really something you can put off. it's way harder to shoehorn them in later
Well, I try to look for the best answer, but if the best answer requieres me to refactor my whole code to do something I am not even sure how it works, cause I am lacking a lot of knowledge, maybe it's not actually the best, at least not for me
That's all I am doing
cause I am lacking a lot of knowledge
because you refuse to learn stuff that isn't immediately obviously applicable lmao
your words, not mine 
Okay, so... do I turn this into a SO dictionary??? Like, I don't even know how to do that, or not even if that's gonna actually help
But sure
Forsure, Don't take that message as combative or anything. I just mean that a lot of the best ways are going to require learning and work and the answers you recieve reflect the question you ask, not neccasarily the reason why your asking the question, if that makes sense
do you know what "future-proofing" is
this is what mine looked like (slightly different implementation ofc)
I try to keep that in mind within the low reach that my absolute lack of expertise allows me, yes
so you basically just stated ignorance of it earlier lol
So, if you find the "related word" it basically makes that word of that color
I wouldn't know how to actually do that lol
In my implementation yeah
I gave you the code too π
A tool for sharing your source code with the world!
This doesn't exactly do what you are looking for as you wanted to define full coverage of aspects of the text inside the text itself
This is also not perfect π
When? I just said this does not really need to be something that is meant to be modifyed on a whimp, so it's fine if it's not very modular
that's exactly what im referring to
it's not that it's not modular lol
welp, can't make a horse drink. if you don't like getting advice then this discussion is useless lol
Oh, wait, can you use a return type of paremeter on SO too?
you can return type on functions
that conceptually could not be limited or restricted to an SO, or class
Then what do you mean???
it's not flexible or future proof and it splits your workflow terribly (in comparison to what it could be)
Quite literally just learnt .Colorize is a thing I can do lol
I wasn't expecting to be needing to use interpolation from editor input, but it happens that, yes, I may need that if I don't wanna do 3000 different scripts for each prefab that needs a different text to be formated
Oh right that function is something i made up, I assume you have a similar implementation
Other than that I think I am doing a decent job (within my limits) of looking ahead
When working with Unity's intended workflow, ideally a majority of values with their values defined should have said definitions managed in the Unity Editor, usually via the Inspector, rather than having them defined in the script itself
Not really, I could tho
look man we're giving this advice for a reason
someone else, sometimes outselves, has already gone through the pain of inflexible code or an indirect workflow
we're telling you this stuff so you can learn the easy way instead of going through the process of fixing preventable issues yourself
I was trying to do that, but it happens that I can not even assign a default reference type to a component
Sprites that I assign as a default value on scripts only apply if added on editor, not in runtime for some reason
yes, that's what they say they do
This thingie, I tried going out of my way to keep it on editor only, and it happens, nope, when you call to add that component, it loses the sprite reference π€·
So.... having all in editor is clearly a no-go
Default references will only be applied in edit mode.
prefabs exist
also more or less the exact purpose of scriptableobjects π
So I have to make a prefab of every single script that is ONLY that script to keep the reference?? That seems basically doubling the space it takes for no real reason
AddComponent really isn't used much in my experience 
the space it takes? why is that a concern at all lmao
Cause I don't want duplicated stuff and then getting all confuse with what is what
if you want every instance of a script to use the same references, why not have them in some centralized place
Isn't that the thinking for the future you say I don't do?
eg. for a card game prototype my individual cards look like this (im in debug inspector to remove some of odin inspectors irrelevent fanciness)
then i just instansiate a cardbehaviour and give it this data reference
then the specific hero the card uses w/ a sprite ref like you we're looking for is in another so
and if you don't want every instance to use the same references, then.. why would you want new instances to have them
or if you want it to be overridable, that's kinda what prefabs achieve
another fun example of a more advanced implementation
Mmmm.... but these are for actual objects right? Like these are prefabs that you are giving the values of the given SO
I want that script to ALWAYS have that image. How would I do that?
oh yeah while you're here, before i forget; you still haven't answered the last question i asked in #π²βui-ux, i still have a partial impl (partial because im not sure what exactly the constraints are) of your question in a test project lol
these are the so's that i give to a prefab yes. the idea is to develop a kind of sibling relationship of the prefab that does things and the scriptableobject that has the values the prefab uses
centralized supplier
you just don't do it that way
overall
Cause I have tried to see the use for SO a bunch of times, but I don't really get in what they are better from an actual script
i think to an extent it's abit of wording/incorrect perception in your head about the word script
a script shouldn't really do or have anything
it's a blueprint/template
an instance of a script (which when working with Unity is usually a prefab) is what does things
so if you want an instance of that script to always have that image, you put it on the instance (prefab)
if you want to separate your doing things and knowing things in order to make your code more modular and maintainable, you would put the image on a scriptableobject the prefab looks at
But... can I even AddComponent with a prefab?
Cause that's basically how this works
You add it to the stuff when called
feels like could be restructured to be a child instead of added directly to the object
the kinda theory behind that sorta goes into the overall responsability of what your things should do.
You need your instance of the script (im gonna call it a prefab) to know about the sprite in order to render it right? But that doesn't necessarily mean the prefab should be responsible for owning the sprite. The prefab does things. If it needs to know something about what its doing it can ask it's scriptableobject for that, because the scriptableobject's job is not doing things, but knowing things
more obvious composition of separate parts
Wouldn't that add uneeded data to it like its transform?
you don't need to worry about that
Respectfully you do not know enough about c# or unity to be able to care about that level of optimisation
unless it's a critical position, readability and maintainability trump performance or efficiency
Like if you need to care about that you need to learn a lot more in order to exist in a workflow that can solve those problems to that extent
I am trying, and absolutely failing, to keep stuff optimized since I am aiming for scalability later, having one child would be no issue, but what if I later want to add like 20?
still, no issue
you start getting issues in the thousands or maybe millions
don't worry about optimization until it becomes necessary
you can preemptively do stuff in a non-insanely-costly way, but don't worry about it
that'd be called premature optimization
(Especially because the solutions to scalability are usually not super simple and up being a lot harder to iterate off of)
This one case in particular I just added this thing, but feels like such a dirty patch compared to how I am doing everything else
Not sure if changing the whole structure to work as a prefab chidren instead of components would be worth to fix that tho
So @sour fulcrum should I turn my TextFormating static into a S0 that can get a string passed and return the translated formating?
Generally you should use SOs for data that's same for multiple instances of a script.
For example you have a SpellData SO that contains the spells name, sprite icon, cooldown, mana cost etc
Now you have your Spell component itself which has a SpellData field. Since AddComponent literally just adds a component, the fields in the component will be empty.
Make a method like AddSpell to which you pass a SpellData and a gameobject, it calls addcomponent and assigns the spelldata field to the SO. With this any code inside the Spell can just check its data from that SO and you don't need to assign things in code
^ In response to this
The actual spells are attached to characters that ARE a prefab and therefore already hold the values, I usually assign the stuff on the prefabs that they have, the issue only comes when I just add them as components, which I usually just pass them the values from instantiation, but the skill does not need to know the icon that the status effects it applies has
it's up to you how you want to do it. Prefabs are fine they're just for that, so you don't need to initialize them in runtime. Components however if not prefab-ized to another GO, you will need to set them up manually, that's why using a SO for them might be better in some cases. For spells, I'm using components and a spelldata. Here you can see that I'm actually reusing the same component for different spells (as the SO holds what kind of cast is used, what projectile to shoot and what attack to fire)
this way I just have this code on my NPCs/Player and by holding a database of SpellDatas I can give a spell to things with 1 line
public virtual void LearnSpell(SpellData data, bool autoSelect)
{
if (HasSpell(data))
return;
var type = data.Type == "" ? typeof(BaseSpell) : Type.GetType(data.Type);
var spell = (ISpell)thisGo.AddComponent(type);
spell.SpellData = data;
spell.Owner = this;
spell.ObjectID = Guid.NewGuid().ToString();
Spells.Add(spell);
if (autoSelect)
SelectSpell(data);
}
It depends on how many spell effects you can fit on the same component for different spells with just SO
if you keep the effect object separate from the spell object itself, you can instantiate any effect for any spell. That's essentially what I'm doing by separating cast/projectile/attack as those are created when you fire the spell
I was actually just using Interfaces/superclasses for that same thing you are doing
for example a Projectile SO holds a prefab of the actual projectile that's fired, you then spawn this prefab to fire the projectile
And you are adding these as object or as components?
doing things this way lets you very easily have object pooling as well for when you have hundreds of NPCs fighting. Instead of always creating a new effect you can re-use the effects that have already finished
Cause adding it as a object I just... go back to the same question, how is that better or worse than a prefab with it's parameters already configured?
SOs are not a component and not a gameobject. You can't put them inside a scene - only reference their file
is that type stuff not abit concerning at scale?
what do you mean? Works fine for me at least I have a bunch of different spells and NPCs
with SOs you can build a small database on runtime which grabs the SOs and then you can use them however you want
how much is a bunch? seems like in your case that function might not be running often
Ye, I mean the spells, not the SO containing the spell data
but if something like this was happening a lot more
the spells are componentss as seen by the above code I sent
honestly i don't really consider that the best example of using SOs. The only thing it's showing off there is adding a component based on a string value. Sure it works but you aren't really showing off how SO's are actually used as data containers
They could be components attached to an object with nothing more π€·
npc/playerdata holds the spells they spawn with. When the npc/player is spawned it grabs these datas and calls LearnSpell
how many npcs tho
I have 11 different NPC types right now
not types
amount of NPC instances? I have made hundreds of them fight but I don't see the point of the question
i was curious about the scale of that functions usage since afaik ideally you want to avoid gettype calls at scale (and casting too9)? but a lot less so)
the BaseSpell can be reused for different spells because of the SO. Creating different projectiles/attacks depending on setup
Quick unrelated question, OnValidate applies whenever you change ANYTHING on the inspector or just checks for the values of the script that has the OnValidate?
the main use case is just as a data container. In terms of the end product you make, it is not better or worse. It is just better in terms of organization.
If you have many prefabs that want the same data, you can modify that data in 1 place (the SO) rather than going back and editing each prefab. I don't really think this is a major use case though. The best part IMO is that it is an asset. You don't need to look through an entire prefab to see the fields you want to edit. It's miles clearly as to what was actually changed in version control too, which you're surely using
im aware of what your code was doing. that really doesnt change what i wrote about it initially
same with attacks, the slow, paralysis and damage are also grabbed from the SO (damage ends up beiung modified depending on stats however)
how is this not a good example of how to use SOs as data containers?
Why reference a type via string and add it at runtime rather than just spawn a prefab of that type?
Well, I don't really find looking on the prefab troublesome, maybe if they are massive
But I kinda like to check where the stuff that I am changing is actually allocated
Maybe I change my mind after doing it 10000+ times
if you end up having lots of spells for example, it will get tedious opening up the prefab and finding the right component everytime. Just seeing the asset based on the name is easier especially if you organize these in your folders with some basic thought behind it. Maybe just try it out here and see how it feels
as long as you're just using it as a data container, you really cant go wrong. If you start following random youtube advice like using it for events then it becomes an issue
SOs a poop. All hail prefab inheritance
for prefabs, that's fine. I have objects (like boxes) in the map that are just dragged into the scene but are also able to be runtime created by the SO with the prefab it holds
for components like spells which NPC datas can hold. The base type (which is just empty in SO) is used almost all the time. If I end up needing to write custom code for a spell I will have to reference it via string in the SO for instantiation. Design-wise? that's a bit eh, I should make a propertydrawer which lets me just select the custom type to use for the spell instead of typing in a string for the type. Ofc I can turn this into a prefab but then I'd have a GO for each spell which I don't see a reason for doing so.
Either way, this has allowed me to pretty much only modify what I need without needing to change it all for other prefabs, so the SO does it's job fine. Learning spells, creating npcs, objects, etc is all done via runtime according to SO definitions, npc spawners etc so in my case this setup is great and I wouldn't remake it unlesss it did get me stuck somewhere
whats the best way to stop sliding down a slope while idle?
like when im not moving, i slowly slide down if i am on a slope due to gravity, how do i make it so i dont slide?
control the gravity yourself rather than letting unity calculate it
uncheck the useGravity field and apply the downward force based on your conditions
and for the slope detection i would use the normals of the surface
thts too much work.. i just turned off gravity when im on slope and idle and it worked! thanks a lot
yeah i am using normals
its quite literally like 2 lines of code given you already detect when you're on a slope. doing it when idle sounds wrong though. You should only need to check the slope of the object below
hmm even if i make my own gravity how will it stop the issue? my condition is still to stop the sliding when im idle, that is to turn the gravity off when im idle
I find it much easier to just control the gravity overall rather than selectively enable it. If you achieve the same result by toggling useGravity then go ahead. Im just saying that it isn't too much work.
Nothing about it is related to being idle. Do you want the character to ever so slightly be pushed down the slope while they're also going up? If you only disable gravity when on a slope AND idle, then while on a slope and moving gravity will still affect them, which is inconsistent. It might not be noticeable, but it doesn't make sense to do
yeah gravity still affecting while im on slope is actually kinda desirable... if gravity is turned off while im on slope there will be this wierd up and down movement for which i have to add downforce again... it works in my favour
thats more of an issue with how you coded your movement then, and not gravity
that issue still exists, it may just not be noticeable in your current setup. if at any point the player can move faster, it'll be noticeable again
yeah im changing drags here and there and all that nasty stuff, right now it works and im going to leave it like it is
true true... i'll switch to what you told if i ever face an issue... thanks a lot for you help!
for that issue specifically, you need to project your movement vector onto the slope. decent tutorials should cover this but basically you'd rotate the vector so it's actually pointing up or down with the slope
yeah im pretty sure im doing the movement correctly... i've check with debug rays too
well i havent seen the code, but from what you're describing it really seems like every individual feature doesn't work entirely. Some other feature is just slightly correcting the issues or it isn't fully noticeable yet
even on a small scale, you still have the issue that while moving up a slope, gravity is trying to force you down when it shouldnt (since its not forcing you down when idle either). And you have this because of another issue where your movement doesn't align with the slope. Somewhere along the way you are also using drag, im not sure for what here
In Unity2D, I'm trying to move two UI elements around, one child and one parent, but I wanted the child to only appear in certain places of the screen, while the parent is always appearing. I tried using masks, but I want to be able to move both child and parent together always, and if I use a mask, I'm forced to make the UI element I want to hide most of the time, a children of the mask, meaning I either stop making it the child of the other UI element OR the mask be a child of the other UI element, so it would move together and be pointless
{
private GameObject[] newpiececlones;
private Piecesinventoryscript piecesInventory;
void Awake()
{ piecesInventory = GetComponent<Piecesinventoryscript>();
newpiececlones = piecesInventory.piececlones;*
}```
what is null or "not set to an instance of an object" in the * line?
you tell us
ah, it's piecesInventory then
so the object doesn't have the script you're trying to get
Hi, I have a script with a serializable string. I set the value in the inspector, the value remains even during runtime, but for some reason when I try to use it, it's empty.
oh, nvm im stupid, I saw the problem
Heya folks
I've switched over from Godot and unity is an experience to say the least - can anyone tell me how I would change this setting?
In Player settings
Edit -> Project Settings -> Player
can someone please help me with smth, im learning unity and i js want soemthig to display on my console but it just doesnt. The conde is fine cus it basically js printing hello. the script is attached the an object, its in assets. I dont get why its not working
if your log is not printing to the console then that code is not running
so what do i do
well if it is a component it must be attached to something in the scene. beyond that, you've not provided enough info
also one thing that i noticed is that Debug.log stays white so i think they are not inherited properly
its attached to the player(3D Object)
if you mean the syntax highlighting in your code editor, then you need to configure your !IDE π (Debug.Log is not inherited, it is a static method on the Debug class)
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
Can you show a screenshot of your script, preferably as minimal as it can be, and your Inspector in Unity with the script attached.
here it is
Is that object in your scene and enabled? If your console is not showing anything, then your Console might be configured to filter certain messages. Check the buttons on the top of console window
Is the script saved?
no no errors
with saved wdym, yes it appears in my assets and it is saved as a file
omg
i had to resave it for it to take the changes
sorry for the trouble
but why is your Debug.Log white. Do you have the C# and C# DevKit and Unity extensions installed in VSCode?
and Visual Studio Editor package installed in Unity?
Hi, i been wondering
how i can make that for example, an script base has a function, and i want a inherited script to use the same function but with changes, do i have to write the same part of base function too?
that is Visual Studio not VS Code. but yes, they need to configure it like i told them to a while ago
make the base method virtual, then override it in the derived class then you can call base.YourMethod() in the overridden method to run the base method's logic at any point within the override
but i mean, i want it to follow to only some specific parts
like my damage function
this function in the base causes the Actor to lose the needed values of health, deploy some items following a value, BUT ALSO, displays a dead animation and a dead sound along spawning the enemie's shards, wich is a gameobject with lil sprites with collisions
the thing is, i want all enemies follow the basic things like the damage and etc, but i also want it to deploy a custom animation, custom sound, or have some tweaks if needed, like if the damagetype is 1 for example, nothing happens
so thats the thing, how i can make it follow the function but with tweaks?
well a lot of that is simply just assigning different values to variables. and if you need even more modularity then you probably need to split the method up into multiple methods
Hi, I am new to unity. For 2d games, is there a way (scripted API call) to move and rotate loaded scenes relative to each other when multiple scenes are loaded? For example, I want one scene to be on the right exit in one game state but in another game state I want the scene to be on the bottom exit. I donβt want a scene transition where it jumps to each room. I liked this tutorial but need to be able to move each scene https://m.youtube.com/watch?v=6-0zD9Xyu5c
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
For this Unity tutorial, I wanted to build off the last tutorial that covered data persistence and loading transitions. This ...
you'd basically just move all the gameobjects within that scene to move the "entire scene"
Ok, thanks. I had this misconception that each scene had some relative origin and I could place origins relative to each other
I figured would need to transform the objects anyway to βrotateβ a scene
nah, if u load 3 scenes together. they're all using the same origin world origin (0,0,0) or (0,0) if 2D
you can stick em all in a single gameobject and rotate that.. (you could do this via code when it needs to be done)
should rotate all the objects (if they have good scales and pivots)
hi! im on a low-end machine and i got this error when trying to start my game. why? i cant start it again because it saws i need to resolve it first, but there is nothing to resolve, it just ran out of memory
right?
appears that way. never seen the error but thats my guess from just reading it
where do i turn off Input System package? im trying to look for it but cant find it
hi , i am doing this course by gamedev.tv
so after doing the prefab lecture and adding prefabs,
my projectlie stopped destroying itself after collision
can someone please help me
Is this the projectile script? If so, it's confusing because of the class name . . .
In the DestroyWhenReached method, you check if the positions are equal. That will likely never happen . . .
its the script i added to my projectile
You need to check if the distance between both positions are below a certain threshold, like 0.5f . . .
there is quite a bit wrong with that. for one thing it doesn't do anything at all about collisions. for another, it only ever gets the player's position at start so if the player ever moves after that it won't do anything about it
so it was working till i turned the projectile spheres into prefabs
i am so sorry, i stated it wrong
it destroys as soon as it reached the position the player was at earlier
to be pedantic, Vector3 == Vector3 does use an epsilon
yes, that is what i said in the second sentence. it only ever gets the player's position one time in its lifetime and does not care if the player ever moves after that
That is because you need to get the current player position. You only get the player position at the start, but not its updated position . . .
yeah thats the part of the lecture i am doing rn
fixing it
but then it still disappears for the dude in the vid and not for me
yeah but the why isnt it disappearing/destroying itself now it just sticks to the ground
it won't destroy itself unless that condition you set is true. so if its position is not the same as the position that the player was in when this object was spawned, then it cannot destroy itself
unless you provide literally any other information, that is all that can be said about it
fixed
consider not maximizing the game view so you can actually see the hierarchy during play mode and can actually inspect what is happening
His disappears on impact
While mine doesn't
Same code line to line
also you do realize that you couldn't record the video with OBS due to the anti-piracy protections, right? you are not allowed to share any part of the course
It worked for me as well
Till the point I converted the sphere thing into a prefab
I'll delete it
Sent it just for reference
Will keep that in mind
rather than just keeping it in mind, do it
Aren't you quite literally dissabling the whole thing on start? Why would you do that?
the projectile only appears when i enter a "Trigger Volume"
Oh, I see, well, first step when something doesn't seem to work is to check if it's actually being called at all
Above the if do print(transform.position + "//" + player.position); to check both positions on console
There
I need the object to disappear as soon as it reaches that position
And just stay there
inspect the objects instead of ignoring them
The projectiles?
I am so sorry I didn't really get you
First day so sorry if I sound dumb π
yes the projectiles. instead of just looking at them in the game and pretending neither the hierarchy nor inspector exists, you can select them in the hierarchy to view them in the inspector and perhaps get some insight into what is happening
is this what you meant
I must say, if your way of leaning is watching tutorials and blindy copy what they do without actually undertanding why it works and scream at the screen when it doesn't work just to repeat the same thing expecting it to work this time, you... are not gonna learn much...
Saying that as an advice, not criticism
Okay, so, what's supposed to be happening to hide the objects
so the destroy when reached method is supposed to make them disappear/destroy once they reach the position
in this case wherever the player was
What script is this in
i am not copying it
trying to write a code beforehand after the explanation
and then check if its write or wrong
Fly at player
the script added to the projectiles
So it seems that the object is never at exactly player position. It's unlikely it'll ever be exactly there, consider checking distance less than some threshold instead
So, get the distance, and check if that distance is less than some small value
Rather than checking if they're exactly equal
is it something to do with prefabs? cuz it stopped working the moment i turned them into prefabs
From what you've shown it appears to be related to numerical precision. You could also add some logs to see what those values are and if they're what you expect
rather than checking for an exact position you should check that it's within some small threshold
e.g.
if (Vector3.Distance(transform.position, playerPosition) < 0.1f)```
Hey, are the balls supposed to follow the player to the player's position, or travel to the original position of the player?
They are supposed to travel to the original position rn
That's the thing that's supposed to be fixed in the next lecture that's what the dude started doing it rn
Please ignore the slow speed of the sphere
But it's the same exact script
Due to floating point precision, whether or not the object reaches exactly that point is basically luck
So do the suggestions you've been given to make that luck no longer a factor
Found the fix
I just removed it from projectile empty thing (they are called scenes if I am right) and just let them be separate things
I noticed the guy didn't have them like that
I did it so that they were organised but probably there is something more to it that idk yet
Do you mean the parent object
Yeah
Like yk how "create empty"
And then you can keep ur objects under it
No they are not called scenes, the scene is the whole thing... and... yes, I guess having them inside an empty parent MAY affect the floating point enough that the final possition is now different
But that's not a "fix"
Probably because it's thousands of units away, and therefore introducing floating point imprecision
It's just luck
So you should do the thing you've been suggested to do to remove imprecision as a factor
works now
thank u so much for being patient and helping out β€οΈ
What is the best way to code screen shake without using cinemachine? Would I have to use quaternions or nah?
Do a Coroutine that gives the camera slightly different positions each frame
Only if you choose to rotate the camera . . .
you rapidly move/rotate the camera. You can do it by writing code, or using Cinemachine, or using a Tween library, or whatever.
Oh, the options . . .
You should try each method and pick the one that provides the best results (depending on ease of use, customization, and scale factor) . . .
I think I did a superbasic one that took the camera pos and returned a new one with a random +X value on each axis and for Y frames and that's all
Yeah, Iβll give all of them a try
Thanks for all the feedback
That seems pretty simple. Did it work well?
Decently so, not very smooth tho
You could add transitions, but that's a bit harder
Whatever you do, just make sure the camera returns to its original pos at the end
Yeah, I feel like using vector3.moveto would give a slightly smoother effect than just putting the camera randomly
Sometimes you just want a violent shake, so no transition can make the trick
But yeah, you can make a Courutine that gives new positions and when getting a new one do a loop that moves the camera closer to the new one each frame and...
You know, you can add as much as you want, depending on what you are looking for
You can always just animate it, which is a bit weird of a method but hey, works
Honestly, that's the simple way. Use a random +/-offset. If you want smooth movement, you can quickly lerp between the positions . . .
I cant figure out how to add a jump or gravity to my character
We talking camera shake ? https://youtu.be/tu-Qe66AvtY?si=wdX4aSt6QXYZ6F5T
In this 2016 GDC session, SMU Guildhall's Squirrel Eiserloh explores the math behind a variety of camera behaviors including framing techniques, types and characteristics of smoothed motion, camera shake, and dynamic split-screen.
Register for GDC: http://ubm.io/2gk5KTU
Join the GDC mailing list: http://www.gdconf.com/subscribe
Follow GDC on ...
Quite literally just add a rigid body and do and do an AddForce up to it when input
You have like a million tutorials about a basic controller like that
ik but none are working
A million tortillas...
Make sure you do the tutorial which matches the version of Unity you want to program on.
that really does not matter most of the time
especially for things like character controllers
is this even attached to the player character?
yes it is because the WASD move works
although I still cant figure out how to turn the object with the mouse
either
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
because there's quite a bit wrong with that script
i am very new at unity i get stuck in this code
i was shaking when i was trying to walk to a wall so i chance my movement code to playerRb.linearVelocity from transform.translate
but now my chacter stop walking after few sec
any idea?
after a few sec of what
nothing in this code would make it stop
are you also pressing left shift or space?
no when i just start the game and press d its happen but i think dash(left shift) also trigger this stop thing
do you have any other scripts or components on the player?
no
