#💻┃code-beginner
1 messages · Page 692 of 1
i like your examples digi, the one with the cat dishes was also nice
its easier to access clothes on the sofa until the sofa has like 100 clothes on it
yea i missed out on the cat bowl one
fr
yeah u are right but normally u shouldnt get a script from an another script so u need use observer pattern am i right?
i saw it so
and
public class HealthUI : MonoBehaviour
{
[SerializeField] private GameObject healthBar;
[SerializeField] private Health playerHealth;
woulndt it be better to just get the hp and maxhp form this playerHealth?
its not observerpattern
cuz i dont need an event at this point
events are helpful for things like this scenario...
-> why would you update the UI every single frame unless the health has changed from the last value it had...
is an event just when you tell something to call this method when something happens
like a callback
kind of
oh got it
first you subscribe to the event from places that are interested in the event.
then you call the event from one place (or multiple places) which means it will call the corresponding method on all subscribers.
Kind of like when you upload a video on youtube and it notifies every subscriber about it.
@polar acorn i made a projectile which i shoot and used observer pattern but im asking myself if it was better before can u read it?
with observer pattern:
public void OnTriggerEnter2D(Collider2D collision)
{
if (!collision.CompareTag("Wall"))
{
EventManager.SendDamage(new DamageEvent(damage, collision.gameObject, owner));
if (collision.CompareTag("Enemy") || collision.CompareTag("Player"))
{
SoundManager.PlaySound3D(SoundTypes.OnHitSoundEffect, transform.position, 0.8f, Random.Range(0.9f, 1.1f));
}
Destroy(gameObject);
}
}
without observer pattern:
public void OnTriggerEnter2D(Collider2D collision)
{
if (!collision.CompareTag("Wall"))
{
//EventManager.SendDamage(new DamageEvent(damage, collision.gameObject, owner));
collision.gameObject.GetComponent<Health>().TakeDamage(damage);
if (collision.CompareTag("Enemy") || collision.CompareTag("Player"))
{
SoundManager.PlaySound3D(SoundTypes.OnHitSoundEffect, transform.position, 0.8f, Random.Range(0.9f, 1.1f));
}
Destroy(gameObject);
}
}
Okay so I instantiate a prefab as a GameObject using something like:
GameObject BackgroundObject = Instantiate(BackgroundType, transform.position, Quaternion.identity) as GameObject;
Where BackgroundObject is my prefab. That prefab has a script with a SerializeField variable, which I would like to populate with a value when I'm instantiating it.
I guess this might be really easy if you know how, but I'm so lost. Any ideas?
type BackgroundType and BackgroundObject as that script instead of GameObject, and have the script provide a public property/initialization method you can feed values to
[SerializeField] private BackgroundScript backgroundPrefab;
BackgroundScript spawnedPrefab = Instantiate(backgroundPrefab, position, Quaternion.identity);
spawnedPrefab.MyValue = someValue;```
something like this is how i generally do it
Oh thanks a lot
Hmm yes using a method might be the way after all
the take-away being that u can use the Script as the Type.. so instead of a gameObject and then needing to use a getComponent
u can just instantiate it using w/e the class is (and already having that reference ready to roll)
Haha yeah that's probably what I should do. I should have done it to start with, but the thing I'm doing is so minor so it felt like overkill. But yes, you're right.
👍
All set up! Thanks y'all for letting me know about the whole Library/Class thing.
I like the way the bullets are represented in your UI, gives the ammo a very physical feeling
my game has prefab dungeons that are instantiated and then the old one is destroyed to show that your moving onto the next room. my character can pickup weapons and drop them by changing the parent of the weapon. However, the way i have this set up, when the player switches weapons, the parent of the old one is now null, which causes the weapon to not be destroyed along with the dungeon. is there anyway i can change the parent of the wweapon to whatever dungeon room is currently in the scene? ive been trying for a while and cant find anyway
code for holding weapon:
{
if (interact)
{
if (!isHolding)
{
if (collision.CompareTag("Weapon"))
{
collision.transform.SetParent(grabPoint);
collision.transform.position = grabPoint.position;
collision.transform.rotation = pivot.rotation;
weaponController = collision.gameObject.GetComponent<Weapon>();
activeWeapon = collision;
isHolding = true;
}
}
else if (isHolding)
{
if (collision.CompareTag("Weapon"))
{
activeWeapon.transform.SetParent(null);
collision.transform.SetParent(grabPoint);
collision.transform.position = grabPoint.position;
collision.transform.rotation = pivot.rotation;
weaponController = collision.gameObject.GetComponent<Weapon>();
activeWeapon = collision;
isHolding = true;
}
}
}
}```
code for creating next room
{
if (currentRoomNumber >= 0 && currentRoomNumber < 50)
{
currentRoomNumber++;
Dungeon _newDungeon;
newDungeon = Instantiate(dungeonPrefab[0], transform.position, transform.rotation);
_newDungeon = newDungeon.GetComponent<Dungeon>();
_newDungeon.RandomSpawn();
spawnedChest = false;
Destroy(gameObject);
}
}```
I'm attempting to code a script that allows me to move the player camera, but it only moves vertically in a very weird way (idk how to explain it) this is my code ```using UnityEngine;
public class PlayerCameraFollow : MonoBehaviour
{
public float SensX;
public float SensY;
public Transform PlayerPosition;
public Transform Orientation;
float XRotation;
float YRotation;
private void Start(){
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
transform.position = PlayerPosition.position;
}
private void Update(){
//get mouse input
float MouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * SensX;
float MouseY = Input.GetAxisRaw("Mouse X") * Time.deltaTime * SensY;
YRotation += MouseX;
XRotation += MouseY;
XRotation = Mathf.Clamp(XRotation, -90f, 90f);
//Rotation Cam & Orientation
transform.rotation = Quaternion.Euler(XRotation, YRotation, 0);
Orientation.rotation = Quaternion.Euler(0, YRotation, 0);
}
}
you need to change it to Mouse Y ont the second float MouseY
you got it double with Mouse X
glad you fixed it
can someone help me with my problem?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
they already did but tldr
@brazen aurora You should link your question if you are bumping it.
As to your question, if you are passing object between objects that being destroyed, you need to pass it first or hold its reference first by an object that will not be destroyed, like a managing script.
Hi, I am working on a 3rd person controller that moves by clicking. when reaching a height it slides down but is supposed to stay on the terrain, no matter how steep the terrain is
If you are using physics, you need to have enough friction not to slide, or turn it kinematic while stationary.
public class SimpleClickToWalk : MonoBehaviour
{
public Camera mainCamera;
public LayerMask groundLayer;
public float moveSpeed = 5f;
private Vector3 targetPosition;
private bool isMoving = false;
void Start()
{
if (mainCamera == null)
mainCamera = Camera.main;
targetPosition = transform.position;
}
void Update()
{
HandleClick();
MoveCharacter();
StickToGround();
}
void HandleClick()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 100f, groundLayer))
{
targetPosition = hit.point;
isMoving = true;
}
}
}
void MoveCharacter()
{
if (!isMoving)
return;
Vector3 direction = targetPosition - transform.position;
direction.y = 0;
if (direction.magnitude < 0.1f)
{
isMoving = false;
return;
}
Vector3 move = direction.normalized * moveSpeed * Time.deltaTime;
if (move.magnitude > direction.magnitude)
move = direction;
transform.position += move;
if (move != Vector3.zero)
transform.forward = move.normalized;
}
void StickToGround()
{
Ray ray = new Ray(transform.position + Vector3.up * 1f, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hit, 10f, groundLayer))
{
Vector3 pos = transform.position;
pos.y = hit.point.y;
transform.position = pos;
}
}
}```
Hi! I'm a new dev in unity and this is my first game that im making without tutorials and my mouse isnt being Picked up in the game while running, this is for my script to look around. Also its picking up my controller(Xbox if that matters). Oh and my mouse(in the new Input system(and im unity 6)) is action type is Value and control type is Vector 2, the binding is Delta [mouse]
!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/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Okay thx!
Did you set a value for the sensitivity field
Debug.Log($"lookAction: {lookAction.ReadValue<Vector2>()}, sensitivity: {Sensitivity}");
Put this in the MouseLookingAround method and see what it prints
ok
Without using a xbox controller
lookAction: (0.00, 0.00), sensitivity: 2
UnityEngine.Debug:Log (object)
PlayerMovement:MouseLookingAround () (at Assets/Scripts/Player movement.cs:97)
PlayerMovement:Update () (at Assets/Scripts/Player movement.cs:58)
With using a xbox controller
lookAction: (0.25, -0.97), sensitivity: 2
UnityEngine.Debug:Log (object)
PlayerMovement:MouseLookingAround () (at Assets/Scripts/Player movement.cs:97)
PlayerMovement:Update () (at Assets/Scripts/Player movement.cs:58)
Doesn't look like it's a code issue, you'll have to ask in #🧰┃ui-toolkit
Oops sorry, meant #🖱️┃input-system
Its okay lol
It worked out really well. Thanks again! Got a parallax-scrolling going now 😄
btw, it's " ` " not " ' "
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("Jump");
}
if (Input.GetKeyDown(KeyCode.Space) && !IsGrounded)
{
animator.SetTrigger("Jump");
}
does anyone know how i would allow the player to jump when touching the ground and play the jump animation, but if the player is not grounded dont play the animation (if the player is pressing jump mid air). if i use the code on the topthe player can play the jump animation will mid air, but if i use the code on the bottom the player has to press jump mid air again after jumping to actually play the jump animation. plz help
Your !IsGrounded is backwards, isn't it?
! means "not"
It should be if (Input.GetKeyDown(KeyCode.Space) && IsGrounded), no?
What you describe for the second one seems to track with what I'd expect "Pressed space bar and is not grounded" would look like, which is what the code says
if i use !IsGrounded then the player jump animation doesnt play bc their grounded but if the play presses space again mid air the animation plays, i what the animation to play once while on the ground and not allow the player to press space again to play the animation again mid air.
if i use just IsGrounded then the player can spam jump and the animation plays mid air
yeah i mean you're checking if you're not on the ground instead of checking if you're on the ground
then your IsGrounded is broken
ye
You want the player to play while the player is grounded, and you press space, right?
show us how you check/assign IsGrounded
i use raycast down from the middle of the player
i want the animation only to be able to play when the player is grounded and not when their mid air
Then you should check for IsGrounded instead of NOT IsGrounded
did you put to ignore the player collider ? it could be hitting the player still and counting it as Grounded.. show us the actual code
Thanks
i did im messing with it rn and i kinda got it to work but i think i need some help with the animator transitions bc it works now, the player can only jump when grounded but the player can now spam jump and occasionally can play the jump animation while not jumping. i think its bc of the jump animations exit time but i need that to play the entire thing.
idk if this helps
maybe Idle to Jump should also have IsGrounded condition too
just make sure IsGrounded parameter is linked to the IsGrounded in code / from raycast
its hard to tell from here, maybe you should make a video with the animator window pulled up and try jumping so you can see what animator is doing
i will do this
still sounds like your grounded check isn't quite right
sounds like it reaches too far down
is it possible to generate and play audio realtime in unity?
sure
so u would just have like a 1 second loop with like a 0.1 second buffer and keep writing stuff and unity will keep looping through the audio
that's an option, sure
is c# plenty fast enough to do this thousands of times per frame?
ok so it is kinda working, ill prob have a falling animation to transition the animations but you can see sometimes the animation doesnt play for some reason
im watching a yt video about jumping and it seems the best way is to section the jump animation into 3 parts (jump, fall, land) ill add this and see how it looks
is sending data from gpu to cpu pretty fast as long as i do it in large chunks
by fast i mean
not latency fast, but data rate
This probably isn’t beginner level talk if you need proper specifics
“Pretty fast” isn’t a particularly helpful metric
Keeping data on one side is faster but the transfer rate is pretty good
can you call a method through inspector
ive made a test one public but cant figure out how to invoke it
through editor scripting sure
im not sure what editor scripting is sorry
Or using e.g. NaughtyAttributes: https://dbrizov.github.io/na-docs/attributes/drawer_attributes/button.html
Customizing the Unity editor through script
ill check out naughty attributes
you can also use ContextMenu
its less nice looking than a button but requires no extra code beside the attribute built in
( your right click on the component and it shows up)
perfect
ahh ok cheers
How could I make my crouching smoother? I'm pretty sure when I crouch it resizes the controller's height from the center so it drops and then when I stand back up it hits the ground so it snaps. I've tried to immediately move the player down when they crouched by doing transform.localPosition -= new Vector3(0f, number, 0f); but that didn't work. Any help?
use a coroutine and interpolate it
I don't see how that would help since the character controller would still fall when it gets sized down
this is what i want it to do
well because as you shrink the controller /collider you have to also change the Center
Like I said, I tried doing that with transform.localPosition -= new Vector3(0f, number, 0f); but that didn't work. If I edit the center of the Character Controller then the gun doesn't move with the camera.
this dude has good video on it
https://youtu.be/-XNm7dPVVOQ?t=572
Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
Join me and learn your way through the Unity Game Engin...
manually changing the transform sounds horrid
the position should not be touched at all.. all you're doing in ideal situation is shrinking and shifting the collider itself
the weapon thing can be addressed easily after that
the timestamp I linked explains the process
nary an issue with this method and its pretty common
How would I define a parent in code? Ex: transform.position.parent
position is a Vector3. It doesn't have a parent.
Transforms do
How would I find the transform of a parent?
The parent is a transform.
Oooooooh
thank you both
Hey guys, Im trying to serialize some data, ive got it working saving and loading a single float, but now im trying to serialise a class of seralizable data. all of the data is serializable in the data class, and my saving method isnt failing, but when I try to load im getting an error saying that nothing was saved in the file path
I can show my code
in compute shaders its fine to set unsigned integers using the setint method right?
{
public static void SaveGhost (RecordTo recordTo)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/playerGhost." + recordTo.levelName;
FileStream stream = new FileStream(path, FileMode.Create);
GhostData data = new GhostData(recordTo);
formatter.Serialize(stream, data);
stream.Close();
}
public static GhostData LoadGhost(string levelName)
{
string path = Application.persistentDataPath + "/playerGhost." + levelName;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GhostData data = formatter.Deserialize(stream) as GhostData;
stream.Close();
return data;
}
else
{
Debug.LogError("Filepath does not exist in " + path);
return null;
}
}
}
as long as the variable is int and not uint
btw you should not use BinaryFormatter
why is that?
microsoft says its unsafe and now obsolete lol
is there a reason not to just use Json serialization ?
the variable in the behaviour script right? not the compute shader
both
oh, well im using int in behaviour and uint in shader, is there anything inherently bad about doing that
Yeah I want binary to prevent cheating as much as possible
is this likely to bug out sometimes
Its a competitive racing game
yes, you can't set a negative value to a uint
But thats fine, ill look into other methods
is it a multiplayer game?
but as long as i dont its all good
Anything serialized is trivially editable
the ones Microsoft suggests are listed therea
BinaryReader and BinaryWriter for XML and JSON.
The System.Text.Json APIs to serialize object graphs into JSON.
Not realtime but with leaderboards
shader stuff seems to always use int not uint so i guess i will just switch it to int
binary encrypted data is annoying enough to edit to dissuade the general populous
you could do TOJson then use SHA type algo to scramble it
Yah ill look into that
Having the file be in AppData is annoying enough to dissuade the general populous
why are you saving the data to client side and not the server with something like playfab
great
True that, and I will implement a rudimentary ghost validation check to see if its been tampered with, but Im still doing what I can. Ill never beat all cheaters but you know how it goes.
there are many better modern binary formats/formatters
you can just scramble it further with this neat class
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography?view=net-9.0
e.g. protobuf, messagepack
Its just me and my laptop for now, im prototyping because ive never made a game before
I have no server
perfect thanks
I usually do SHA512 and its good enough, if someone really wants to they can decompile it and find out which algo you use and possibly a the Key if you stored it in the same code.. but at least deters regular joes from it
would still recommend this https://learn.microsoft.com/en-us/gaming/playfab/community/leaderboards/
eh unity has one and imo its much easier than Playfab to intergrate
do they?
Its something to look into when I want to get online. I defintiely want an "offline version" so my game doesnt just become obsolete when i run out of server money, so i guess thats what im building now
one small step at a time 🦾
valid will help when thinking about if SKG passes
the free tier is pretty generous
you probably wont ever run out unless you get insane amount of traffic, and if that were the case you should be earning enough for it lol
probably gonna release my game for free
im just enjoying making it i dont care about the money
but i see your point
fair i never really look at their products cause im lazy
they have good stuff like Cloud saving and all that jazz
though off topic how do i get unity to register earnings? cause i've made some money from selling a game off itch.io but unity still says $0
The unity one would probably be fine, as long as theres enough documentation for me to start understanding how to use it
I think they rely on a trust system or something lol
Also if it lets me upload and download my ghosts
where would i go to report earnings then?
I'm working on a couple of example projects / vid im throwing on github, the docs is good for the UGS stuff but doesnt go in the details as I'd like them to so I'm trying to bring that out
why do you need to report earnings to Unity exactly?
I guess in your dashboard somewhere, I have no idea where though.. I have made 0$
what is UGS
fair not like i've made enough to care
oh sorry they call it just Cloud now, basically their Unity Gaming Services, but yeah its just Cloud now
no reason :/ just figured unity might not like me if i just never did
Oh I see, thanks
Im on a bit of an island with this stuff, im not familiar with these terms haha
The only thing you have to do is if you reach 200K USD in revenue you have to use Unity Pro and if your company's total finances exceed 25 million you need Enterprise. https://unity.com/products
no worries with time you will
so they really dont care otherwise
nope
Great i can keep me and my $5 to myself
Yeah its a slow process but my day job really slows down in summer so i get more time to focus on hobbies. The more time I spend in this server the less I feel like an alien 👽
we all been there at some point 😄
I'm 5 years in just about and still feel like I never know enough
Ah thats a vibe, I teach sports and whenevr people hit that 5 to 10 years amrk they start realising that they dont know anything about their sport at all haha
you start going from Dunning-Kruger effect to Imposter syndrome lol
What if I make 199.99k?
Sorry forgot to turn off the ping, my bad
There is no way of removing parameters in a subclass that exist on it's parent class right?
"parameters" are things in the parentheses for a method. They don't exist on a class
do you mean fields?
I basically want to do a variant of an inventory item that does nothing at all, a dummy
All subclasses have all the members of the parent class
Yeah, as I expected, well I have no clue on how should I refactor this then
Perhaps show the code and explain what you mean in context?
This is an inventory that is filled with items of the type "gear", the last one is meant to be a "dummy gear" that isn't meant to do anything at all, it's just to fill the empty cells. My idea was to keep the dummy as gear type to simplify the lists that hold and display the inventory. Gear does a bunch of things that I do not want the dummy to do at all, so I am wondering what would be the best way to make a dummy that does nothing but it's still a gear type
A better model is:
class Inventory {
Item[] items;
public Inventory (int slots) {
items = new Item[slots];
}
}
abstract class Item {
// item stuff
}
class Gear : Item {
// gear specific stuff
}```
using an array you can simply leave null slots in it
null slots would be empty slots
then your presentation layer (the ui that displays this) can handle things as needed
It's not like you have a fixed amount of slots that you can fill, it's meant to expand indefinelty. The dummies would expand to cover 1: the last unfilled row; and 2: the full viewport they are in if the items you are currently holding are not enough to do so. It's just so you can visibilly see there is supposed to be something there and it's not just a full empty square lol
sounds like something your UI code needs to worry about and your actual data model doesn't
I think you probably haven't established a clear boundary between your data model and your presentation layer
which is going to bite you
Could potentially use an interface to dumb this down even more right? Like a ISlottable or something. Then Have Item and your “empty” class implement that
Depending on what the Inventory needs to know
Yeah, I am having kinda of a mess of structure rn. Like I am working on it
I am not even sure how to separate the gear on the UI that has visual elements and all and the one that is just a component that is meant to be attached to whoever is using it
But right now, I am with the arrangement of this inventory
The thing is gear is already currently inheriting from another class that is "tooltipItem", can I still give it another parent class?
Should be an interface right?
It cannot inherit from two classes
Cause in here, first, why an array? Second, I would kinda have to juggle with the fields of the gear items on the array to sort them, so make it an array of Item instead of gear kinda complicates it???
The array was to allow for empty slots as I explained before. If you don't need them, a list is fine
I would kinda have to juggle with the fields of the gear items on the array to sort them
Array vs list doesn't complicate the sorting process at all
I mean making the List/Array of the type Item instead of Gear
The UI element representing the item in the inventory UI and the item itself are not and should not be the same object
I don't really know the relationship between Gear and Item in your game
I was just guessing
Yeah, I kinda coded all togheter cause I am dumb af lol
None, "Item" does not exist. And Gear and Characters is basically all you are ever going to have in an inventory. I guess they could both be "Items" since they would use similar logic on the UI
or you have an ItemSlot which can reference either a Gear or a Character
and your inventory holds ItemSlots
It would then be quite easy to have an empty ItemSlot
And.... ItemSlot would be... what? An abstract parent class?
no
just a class
with fields
ItemSlot {
// only one of these two would be populated
Character character;
Gear gear;
}```
Methinks you jump to inheritance too eagerly
I am inheriting quite a bit, yeah
But shouldn't I? Considering both of those are basically always gonna be linked with an ItemSlot, why not making it part of the thing directly?
What's the criteria for that?
why would they always be part of an itemslot
do your characters and Gear not exist other than when you're looking at the inventory menu?
An "ItemSlot" in this case is like a shelf
just because you put a candle on the shelf, it doesn't mean a candle is a shelf.
In this case, is more like "candle that can only exist on a self"
Those items are referring the UI versions of them, they cannot exist outside UI, in this case the shelf
Like the actual usable gear cannot have like a graphic component that is meant to show in the UI, it just does stuff
reminds me of enums, i love my enums
all my homies hate enums
let's say, I have a prefab like this, and then I change something on it:
like, the location of an object
Does that cause the location of every instance of that object on all prefabs to also change?
If the position is relative to the parent object, yes; that's the point of prefabs
Remember to overwrite tho
If I don't overwrite, does it only change the position of this specific instance of the prefab?
Because it’s an instance of a prefab you’d need to explicitly press in it’s inspector to overwrite the asset of the prefab with those changes
You can also just click the prefab itself and edit it on the void
Rather than on scene
Ideally you wanna prefer to handle those exempt differences via setting them in code than handling them via instance differences though, just because it’s easier to manage and validate
thanks, that's what I'm looking for. modifying something from a prefab without changing all the other instances.
Yee
that's true, but I'm kinda fumbling around right now to just figure out how unity editor works.
Yeah all good
another basic question, what is that icon that looks like the prefab icon but has a {} in the lower right corner?
like, its name
You mean... scripteable objects?
I, have, still, not successfully used any over a prefab actually lol
ScriptableObjects are ways to make “templates” of data that you’d usually reference in a script/monobehaviour. They are usually used to separate data and logic.
Eg lets think about Minecraft
You might have a Block MonoBehaviour class that exists for every block in the game. Rather than having say “Cobblestone.png” in a prefab for every Block type, you could have Blocks keep a reference to a ScriptableObject class named say “BlockData”. Then BlockData can contain the texture, name etc. per block type
Basically it's a script that is saved as like a prefab without needing to attach it to anything, pretty much
How is this clearing the list but not destroying any of the items without sending any error message?
what is currentDummies.are those editor stuff?
It's for quick testing
It's meant to the normal destroy
CurrentDummies is just a list of items that do nothing
Oh, no, of course, I am destroying the component, not the gameobject, fuck I am dummie myself
I'm having an issue with my interacting system, would be grateful if someone could point me to the direction of fixing it 🙏
Interact function, the ray seems to be hitting and calling out the door, but it doesn't see it as a IInteractable somehow.
{
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out RaycastHit hit, interactRange))
{
Debug.Log("Ray hit: " + hit.collider.gameObject.name);
if (hit.collider.gameObject.TryGetComponent<IInteractable>(out var interactable))
{
Debug.Log("Interactable found.");
UIManager.Instance.interactText.text = interactable.interactionPrompt;
UIManager.Instance.interactText.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("Pressed E on: " + hit.collider.name);
interactable.OnInteract();
}
return;
}
}```
for reference, this is my IInteractable.cs:
```public interface IInteractable
{
string interactionPrompt { get; }
void OnInteract();
}```
and this is my Door.cs:
```public class Door : MonoBehaviour, IInteractable
{
[Tooltip("Animator controlling door animations")]
public Animator animator;
// Default state of the door
private bool isOpen = false;
string prompt = "Press E to open door";
string IInteractable.interactionPrompt => prompt;
private void Start()
{
if (animator == null)
{
Debug.LogWarning($"Door '{gameObject.name}': Animator is not assigned.");
}
}
public void OnInteract()
{
isOpen = !isOpen;
animator.SetBool("isOpen", isOpen);
Debug.Log($"Door '{gameObject.name}' {(isOpen ? "opened" : "closed")}!");
}
}```
Everything seems to be linked and correct yet when the ray hits it doesnt see the door as a IInteractable
the door script is linked to the parent door, which is Door - DoorHinge - Door (The model)
whats it hitting
also if you define the type on the out variable you don't need to define it in the generic which just looks better, eg.
thing.TryGetComponent(out MyType myThing)
not something that matters but just nice to know
oooh nice
I put the DoorHinge and the Door on ignore raycast layer
now all thats left for the ray is the parent door
seems like the ray isnt hitting now
it does hit the 2 cubes next to it
this is the parent Door
I think im stupid
There’s nothing to hit 😄
the parent is an empty gameobject, therefore no collider, therefore ray not hitting
so i should put the script on the door model itself huh..
i just realized it hahaah im testing it right now lets see
Or have the collision as just a box collider on the root
If the door is just a simple rectangle
it just rotates 90 degrees
the hinge rotates itself and the model with it
is there a way to stretch the collider on the model?
or do i need to manually do it
can anyone help me understand why when i start up the game, my door opens automatically? 
isOpen is unchecked = false
show the transition DoorClose to DoorOpen
figured it out a minute ago 🙏
@rich adder wanna help me with a different issue
I have this isOpen bool, and i want some doors to be automatically open at the start, so i created a new transition from Entry -> DoorOpen (on isOpen = true)
but when i start up the game with a specific door that has isOpen = true, it doesnt open at the beginning
in the code or the animator controller ?
in the inspector, on a specific door
the isOpen default is false
{
isOpen = !isOpen;
animator.SetBool("isOpen", isOpen);
prompt = ($"Press E to {(isOpen ? "close door" : "open door")}");
Debug.Log($"Door '{gameObject.name}' {(isOpen ? "opened" : "closed")}!");
}```
so lets say it has isOpen = true at the beginning, i think its problematic because interact make it false, and then puts the animator on false too
because its code problematic, i just made an animator transition
you dont call animator.SetBool in start ?
hello there. do dynamic buffer support paralel like native list or nativequeue, like this"public NativeQueue<T>.ParallelWriter"?
i will, thanks bud.
i have so many scripts. can i somehow in editor look for like "PlayerCamera" and it finds every script that contains "PlayerCamera" ?
and it finds every script that contains "PlayerCamera" ?
via whatever IDE your using
VSCode
not sure how it works in code but in studio i can right click a type and go to find all references
You can find references in vs code as well
Vs code provides most of the same features as VS nowadays.
found it
Ctrl + t or something. You'll need to check the shortcuts. Or in the context menu.
its ctrl + shift + f instead of ctrl + f
feel free to keep using code but studio can be pretty close to that layout, just for reference
That's a regular search
That search is terrible lol
Oh for sure, I'm just ragging on VS Code 🙂
i used to do webdev and i like vscode for that
I'm a web dev and in large React apps, VS Code is terrible for go to definition - constant loading progress bars. Webstorm's much better (for me)
i just started learning webdev, was good for my use xD but im not up to date at all
like 10 years ago i used that...
microsoft expression web or so
xD
I press Ctrl+T for this.
i use vscode and so far got no problems
but you can do ctrl+shift+f yeah if that's indeed what you want 😄
i rly need to cleanup all my scripts
I usually just go to the var with ctrl+T, then find all references
also idk why but whenever i put a script on a gamemanager i always create a new gameobject instead of just having 1. i think thats a big fail aswell 
You'll hit them (eventually). I jump between Neovim and Jetbrains these days
not terrible imo but yeah one feels less bloat-y lol
I keep my project's hierarchy as minimal as possible, but back it up with behind-the-scenes logic (like scene initialization, editor scripts, etc)
my hierachy is horrible lol
Takes 2 minutes to cleanup 😉
hmm yeah I meant in scene/hiearchy but nice 😛
seems fine here x)
yup! quick fixup is just drag & drop everything non-scene related into a nested prefab and instantiate it on startup 😄 Keep the "scene" as a "Level"
hi ive got a slider for my ui which on value changed is hooked up to a function with a float parameter altho the value of the slider isnt going into the parameter
can u send a screenshot of the component?
yup, so, you're already passing a fixed value there, that's not correctly setup
ah
what's the definition of AudioMixerHandler.UpdateMa....?
{
SetVolume("MasterVol", value);
} ```
try pressing the [-] button and reassigning it, idk 😛
wdym
the minus button here
yup!
cool nice
#1390355039272439868 for general discussions. Advanced got merged with general.
So, I'm doing this beginner unity tutorial for a 2d platformer. I have run into several issues at the timestamp in the video:
- in her code, rb.velocity & rb.velocity.y don't exist anymore in my current version of unity so I replaced those with rb.linearVelocityY. Is that correct? Why or why not?
- I'm getting a blue information hint in the error list, that my start is empty. Is that supposed to be that way at that point in the tutorial?
- I'm getting a error that says 'moveSpeed' doesn't exist in the current context, but in the video her code seems to work fine. What's up with that?
Video Link with timestamp & screenshot of my code:
FREE code for this video on my Patreon
In this episode we'll be getting our player moving using Unity's 'new' Input System!
We'll be working with the Input System throughout this platformer series, so check out our future episodes for more implementations.
❗️❗️❗️📢 BUY THE COMPLETE GAME TEMPLATE NOW!!! 👾❗️❗️❗️
...
- yes, Rigidbody2D.velocity was renamed to Rigidbody2D.linearVelocity, as was the X and Y counterparts to that property (which were also added fairly recently)
- if Start is empty at that point of the tutorial then yes, your Start should be empty as well and the IDE is simply telling you that it is empty
- You are getting an error because you spelled it wrong
what is rb.linearVelocityY? 😛 You probably mean rb.linearVelocity.y
huh, cool
but yeah about the moveSpeed (vs movespeed), as a programmer you need to learn to type less and use auto-complete more 😄
When I build my Unity (web) application, I would like to execute a post-build bash script. Where should I be looking to find info on this?
ahh thank you!!
Thank you
https://docs.unity3d.com/Packages/com.unity.test-framework@2.0/manual/reference-async-tests.html
Anyone know how i would do
yield return new WaitForEndOfFrame()
using the new async tests?
If you're on unity 6 or later then there's the Awaitable class that has the EndOfFrameAsync method you can await. otherwise you'd need to use unitask or a coroutine instead of a Task
Just organize it like I did!
wow :o this looks good.
It's better to use Visual Studio to tell you the truth, it's less complicated than VS Code for me.
Just two cents, I'd personally have the stuff like post-processing, vfx, managers, UI, etc. above environment, lighting etc. since there a lot smaller and environment and such tend to expand into pretty big groups of objects
keeping the messy toybox at the bottom so its easier to find the important stuff 😄
Yes my unity editor layout is different my hierarchy has a lot of space
Check how much space I have
I've had scenes that would have a fully expanded environment tab fill that space 9-10x over 😄
I love organization btw
I cant work on a messy environment
XD
Its for productivity purposes basically, it improves the workflow and production
Hmm but my tests are getting stuck on the Awaitables. I'm using the test runner 2.0 and using [RequiresPlayMode]. Any ideas?
And I'd recommend Rider 😛
If you want to pay yes probably XD
I recommend Visual Studio for free it's the best option.
People might want to pay in order to get more features to expand, but really if you are a solo developer and you are a beginner dont have a team yet what's the reason to pay
it's not easily possible, this is the version unity ships with
i wanted to try struct tbh
why that wasnt a thing earlier on annoys me 😠
How can i know what the object im over in ui if i know Input.mouse position?
raycast from the screen?
i can do that on UI??
If they have colliders
that's what the block raycast thing is for
though if you're using Input you could also use the OnMousex events i think
RectTransform rt = TextureImages[LayerOn].rectTransform;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, screenPosition, null, out Vector2 localPoint))
return;
Vector2 pivotAdjusted = new(localPoint.x + rt.rect.width * 0.5f, localPoint.y + rt.rect.height * 0.5f);
float scaleX = rt.rect.width / TextureLayers[LayerOn].width;
float scaleY = rt.rect.height / TextureLayers[LayerOn].height;
int texX = Mathf.FloorToInt(pivotAdjusted.x / scaleX);
int texY = Mathf.FloorToInt(pivotAdjusted.y / scaleY);
if(texX < 0 || texY < 0 || texX > TextureLayers[LayerOn].width || texY > TextureLayers[LayerOn].height)
{
Debug.Log("Out of bounds");
return;
}
Debug.Log($"{texX} : {texY}");
i am
i saw that, which is why i brought that up
that's for physics raycasts, i'm referring to graphics raycasts
so how do i raycast on ui??
ive tried GraphicsRaycaster but its just weird idk why
oh it appends 😭
Is it so much of a big deal to use obsolete methods or properties?
Hi, if anyone is using NGO Lobbies, did it happens to break for you too? Just got this error rn but it worked fine since a few weeks:
you won't be able to build with some of them iirc
why tho? doesn't it still work?
some work in the editor, but not in builds, afaik
same issue here
Seems like unity just pushed something they souldn't have
Are you on the LTS NGO version too?
theres a forum for multiplayer related stuff #1390346492019212368
NGO & Relay
the Unity Multiplayer Services package
the --------------- kinda crazy but its aight
in compute shaders is there some cheaper texture u can do that has just 1 channel instead of 4 channels
oh ig u just set it to uint or something there right
How do I get a forced 60 FPS without turning VSync off?
If vSync is ON you will get synced to your monitor refresh rate
there's no avoiding/changing that with vSync on
(you can definitely still get LESS than your monitor refresh rate, but not more)
If you wanna cap it at 60 you can use csharp Application.targetFrameRate = 60;
Yeah I have that line of code and VSync off but then it causes screen tearing
Iirc it means that you are rendering frames faster than your monitor can
Do you still have tearing with Vsync on?
I don't believe so, but VSync on caused all the WaitForSecond code to not work on someone else's PC.
Sounds like you wrote framerate dependent code and should fix that instead
yeah probably a time.time instead of deltaTime somewhere
Sounds like you have a major bug to fix before it's done
or things in update that should be in fixedUpdate
It's not really worth speculating on what the exact issue is without getting an explanation of what's going wrong and seeing the code involved
I thought modern platformer games had forced 60 FPS so that things would work.
definitely not
Sure but its the most common errors
you can't "force" a specific framerate in practice, the real world is unfortunately messy
They may certainly be using FixedUpdate or an equivalent for their physics calculations
but they don't force a framerate
is there such thing as something like a render texture but super cheap with no bloat like mip maps and depth buffers and rgb channels, just a grid of integers or floats
single channel
would it be best to just use an array?
somehow
sounds like a question for #1390346776804069396
not to worry chat gpt helped me out
guys what vsc extensions should i downlod?
!vscode
Hello guys!
Trying to make a script to solve a math operation with 4 variable integers and 4 variable kinds of operation (+, -, ÷, ×), trying to find a way to make it without having to make a hundred IFs and Else IFs
is the fastest way to get gpu to sample average value in a texture just to get it to generate mip maps and read the 1x1 texture
like chris said earlier, probably a question for #1390346776804069396
forums are the best way to wait 5 hours to get an answer to a yes or no question lol
it has a general thread too
ahh ok i didnt see
could you give a little more detail? what's the operation look like
- (V1) - (V2) × (V3) ÷ (V4)
But the kind of math operation will be a Variable too
But not sure on how to do this
You could use delegate for the operations
Trying to follow the PEMDAS order of math operations too
if you allow arbitrary parens you can just ignore pemdas for the calculation
I want to learn C# only limited to unity ( i have programming expierence and how coding works inst new to me)
Any PDF i can refer to which explains it step by step?
I had downloaded one but its quite old sadly
I am not sure how many changes have been name
Alright
thanks!
I'm curious what you found that was so old that it wasn't worth using. was it a 20 year old book or something?
Can't you just use DataTable.Compute(expression, ""); ?
The UI they used for their screen shots was very old version (They also mentioned "Unityscript")
iirc it'll even follow PEDMAS
I am new to this and am not sure how old these things are
i just dont wanna take the risk 💔
Bettter take advice rather than messing up
ah, so it was a unity course, not a c# course then. learn c# separately from unity first and you'll have an easier time following along with unity tutorials
I have this issue where when I stop moving the ball is still spinning. https://paste.ofcode.org/UkrYHrEQXFq8L9Pycd6dXn
any ideas on how to fix this?
well, make it stop spinning?
increase angular drag
or add angular drag/friction
Well, the code you shared doesnt have anything to do with it spinning, that spin clearly happens before you even start moving
we don't do DMs here, it defeats the purpose of having a community server
just !ask about your question
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
your question is incredibly vague. You should share how your game is currently set up, your current code, and a good explanation of what kind of movement you're trying to achieve
and post the relevant !code you're having issues with
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ok sorry
well im trying to make my first game but the code wont work and im not sure what to do got this from a guy on YT
first off, configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
secondly - be more specific. you wouldn't be here if it was working, we need to know how it isn't working
are you getting errors, is it not doing anything, is it doing something you don't want it to do, etc
its not doing anything
Check your console window for errors
most likely if this is a new project, your project has defaulted to the new input system
ive done that
and this code is trying to use the old
You've done that and...?
What was the result?
What do you see there?
We are not mind readers
well nothing happened
Did you ever attach this script to your player object?
maybe the script is not attached to your gameObject
probs
I can literally see an error from here
what does the error say?
probably something about the Input class
🛑 red means error
if you have errors , well things dont work as they should..usually..
I have this issue where when I jump I reach the normal height and then when I do it again I go higher for some reason
show code
you likely need to reset the y velocity to 0 before jump
try this maybe?
var vel = rb.linearVelocity;
vel.y = 0;
rb.linearVelocity = vel;
rb.AddForce(Vector3.up * jumpHeight, ForceMode.Impulse);```
the issue is still there and the damping doesnt go to 0 when not grounded
is the minimum vertex distance property on linerenderers deprecated? i can’t seem to find it in the inspector
can you try moving the Spherecast in fixed update instead?
like this right?
the issue is still there. https://paste.ofcode.org/STZhpwXwnupbm7YnW5tfPv
its like a weird spring jump
first time seeing that tbh. I wonder if its thinking it was grounded a couple of times while jumping
btw unrelated somewhat...most of the move code should be in fixed update..
always move rigidbodies in fixedupdate (unless its Impulse then its ok in update)
btw something nagging me but why do you use input getaxis when you also use new input system 
oh so I should put my handlemovement in fixedupdate then?
usually yeah
you should change any deltaTime to fixedDeltaTime as well pretty sure
correct me if I'm wrong
deltaTime turns into fixedDeltaTime when placed in FixedUpdate, although they should not be used with AddForce / .Velocity
rigidbodies are already moving on a fixeddelta (unless you use MovePosition but thats for kinematics)
so how can I fix this issue? also the lineardamping doesnt change as well
cant fix issue if you dont narrow down the origin of the issue
honestly I'm trying to find what the problem is and the only solution I can thing off to fix this is to add a jump cool down so the player doesn't spam jump which I was going to add anyways
kinda goes with this thought I had before .. there might be multiple times being read as grounded while going up giving it extra boost
Hello
howdy.
Not a 'Social Chatroom', so, "hi" and "hello" generally go unanswered.
If you have a Unity question, feel free to !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
I may have fixed it! https://paste.ofcode.org/35kdx74VsdK278VP2S53Jvw
well it looks fine now
doesn't do that springy jump
im trying to code this plane to fly and the tutorial said that once i code this part the plane should rotate and pitch but when i pressed play it wouldnt do that
Better to post !code since this screenshot is somehow very blurry.
Also you have errors, you should probably address those (or at least not crop them out) before you start trying to figure out why the code is doing something odd. The errors could very well be the cause of that
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
the damping part ?
it says something about ActionBasedContinousturnprovider and how it was let go in 3.0 but idk how to fix it cause when i press it, it sends me to a code i didnt work on
yes
I added
else { rb.linearDamping = 0f; }
and it fixed the issue I was having
i get this error when im not hitting any cllider but the if is still going trough, i tried doing hit.collider != null but still and also even when the colliders tag is diffrent i still get the message any ideas
show the script your using
!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/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its kinda long and prob bad but dont juge okay 
Did you check if the raycast actually hit anything
thats the problem
you need to null check hit.collider before calling any methods on it
and how do i send big lines of code?
layermasks in raycasts are very usefull
which is line 143
89
Your hit.collider.CompareTag("Enemy") isn't even inside of a raycast condition
yeah so this is still the answer then #💻┃code-beginner message
it was at first but then the attacks couldnt go trough if im (exsample looking at the sky)
makes sence
you could actually move the code into line 56 if statements
i think im not made for coding
start small, this is not easy
evry time i try to get help i relaise how stupid i am
i did
you are not stupid, you just need more practise
i have been trying to learn for over past 1 and a half
mhm
so it is easy you can not just use hit because it doesnt exist in that context. but you have it a few lines higher so you could put the code you want into that if statement
right, well "learning to code" does generally take quite a bit longer than that
you may be getting in too deep for yourself
if (Physics.Raycast(cameraTransform.transform.position, cameraTransform.forward, out hit, 10f, resourceLayer))
``` hit only exists inside this if statement
are you following a tutorial?
i get that the code was in the raycast but then the attacks would go trough if i didnt hit the resorce layer so im just gonna put the raycats inside the attack function thoes that make sence?
no
you probably should
technically that is not the case. it exists outside of it as well, it is only guaranteed to contain valid data inside that if statement
never gonna leanr that way
you aren't gonna learn if you're just stumbling randomly until it works either
get some actual structured learning
ph right he declared the Raycast outside sorry missed that
there are resources pinned in this channel and in !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
even if it were declared inline it would still be accessible through the rest of the same scope that if statement is contained in
"tutorial hell" is not caused by using tutorials, it's caused by using tutorials without trying to learn and understand what they give
i did learn for a year C# without tuching unity
and have you used it recently?
then i made some small projects first without tuorials
now im donig something little bigger
i used some tutorials on the basic stuff
you mean for unity or c#?
C# for unity
gotcha..
when i said inside this if statement of course i ment inside the scope / body
footnote: that is contextual to how the function works and is used
if you negate the result, then the raycasthit is only valid in the else, or outside the if if there's an early exit, eg with a guard clause
yes, and the variable would be accessible outside of the if statement's scope. it would be accessible anywhere within the same scope that the if statement itself is in
{ // outer scope, out parameter is accessible here
if(Raycast(out var hit))
{ // inner scope, out parameter is guaranteed to be valid here }
}
Yep because the out var sugar syntax basically just places a variable right before the if statement that it writes into 
Allows you to do neat stuff like
if (!Raycast(thing, out var hit))
return;
// 'hit' accessible here
I like to always read/interpret guard clauses as "only continue if `[condition]"
reduces overhead for me
i even always write the return in the same line as the if clause because that way I interpret them as a whole stament (only continue if x)
Im gonna assume that this is the correct channel for this,
I was wondering whats the best way to make a pickup system i dont want code or anything just like how i could maek it
pickup system is pretty vague...different methods used for different styles
most typically its done with some sort of physics query , casts , overlap etc.
Okay thanks ill see what fits best
Things like OnTriggerEnter let you detect if your object has entered another object's area, which can be used to detect if another objects in pickable range. Since physic is overall slow, you can alternatively create some manager that will iterate through pickable objects and check if their close enough to the player (calculations may include radius of both objects). For best efficiency you could base it on some sort of quad tree, but I wouldn't bother unless there are hundreds of pickable objects and multiple pickers.
Alternatively, you may implement pick up on mouse click. In such case you want to use OnMouseDown method, or combine OnMouseOver with some input detection. Alternatively, you can cast a ray from the camera, check the intersection with a plane, and check how far it is from pickable object.
Well the game will(one day) have multiplayer(up to 4 or 5) so id need a system that wouldnt interfere with other players and can be used in a client host enviorment, and there will be a decent amount of object in a scene so by the looks of it a quad tree would be the best option. Wdyt
how do i check if a gameobject is in the scene, even if it's disabled
if(mygameobject)
// gameobject exists```
wouldn't that still return true if it existed in assets?
yeah if thats what you referenced I suppose... maybe explain what you're trying to do exactly, it be easier to recommend alternative
GameObject find Methods exists and they search the heirarchy, but generally not recommended to be used often cause they're slow
i want to differentiate between references to gameobjects in Assets, and references to gameobjects which are actually an instance in the scene
It will return true if the specific instance you are checking exists
If you drag in an asset, it will check that asset. If you drag in a scene object, it will check the scene object
right. how do i differentiate between an asset and a scene object
How are you referencing it?
through a serialized array
toSpawn
And what did you drag into it? An asset, or a scene object?
I believe there is also gameObject.scene.isValid() you can do
well, that's the thing. i want my code to be able to detect the difference. i would like to instantiate toSpawn if it is not already in the scene, but if it IS already in the scene, i do NOT want to instantiate it, and instead only run ActivateSpawned
just put it in a List when you spawn it then check the list?
Then you are going to need to maintain some sort of association yourself, through something like a dictionary. Instantiate creates a wholly separate clone of an object. The list still contains only prefab assets and it has no relation with anything copied from it
i think you're misunderstanding. sometimes, i will put objects into spawnOnDamaged which already existed when i started running the scene, and were not put there by code. i do not want to instantiate another clone of these
Sounds to me like you should just have two lists
Things that need to be spawned, and things that need to be activated
...i refuse because i am stupid
Hello im following a tutorial right now and I am trying to do something very simple.. I have been trying for HOURS to do this fucking shit and its starting to stress me out a lot can someone please help me.... Im attempting to use OnCollisionEnter2D inside a script named Player, the player script is attached to a rabbit that has a rigidbody and a box collider... the rabbit is supposed to run into carrots and the carrots are set to destroy and increase score. I even put in print("object collided") and nothing happens
The carrots only have a box collider on them
All of it is 2D and i havnt found anything wrong with the script code at all...
the carrot is tagged Carrot and everything is spelled correctly i checked 100 times
Show the inspectors of both objects
show the OnCollisionEnter2D method
the script code?
ye
here is your problem
a misspelling??
it's a Capital 'O', OnColl...
OMG XD
configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
You should put the print() method at the very top of your method next time
I corrected the O and its still not working
configure your ide and then put the print outside the if statement so you can pinpoint where your problem is.
it's also Enter2D not Enter2d
yes I need to also fix that whats the best way to configure it what options do i go to?
@polar acorn , @eternal needle , @eager elm thank you so much for helping me
So it was a mispelling the whole time
Yeah I dont know how to configure and fix the studio im using Microsoft Visual Studio
read the bot command, it tells you
Wait….. you can use print in unity?!?! I thought it was only debug.log?!?
how can this output a completely black texture
if i do result[id.xy] = 1.0; it passes the full white test
print is a function. you can call functions yes https://docs.unity3d.com/6000.1/Documentation/ScriptReference/MonoBehaviour-print.html
theres no point though because you cant pass a 2nd parameter like u can in debug.log
#1390346776804069396 probably
Ive tried and I still cannot figure out how to fix it...
for some reason I'm not able to set these game objects to be active or inactive in code.
here's what I've tried:
- making sure that the correct, prefab specific game objects are what's linked in the inspector (they are the correct objects)
- printing a statement that tells me when an object should be disabled (they disable correctly based on my test parameters)
- manually hitting the checkbox at runtime (it disables and enables just fine)
is there something really obvious I am missing here? this is mystifying to me
from reading online the only "gotcha" I can find is that a disabled object stops its update loop but this is just about getting the objects to correctly disappear and reappear
wondering if this has anything to do with the fact that the children are model variant prefabs
argh, it was something silly - was running the code on the prefab to instantiate and not the instantiated prefab 😛
I'm not sure if thsi is the correct channel, but I'm trying to have multiple grids in my scene. Could someone help me out? 😄 i can only see one grid
Or correction: is it even possbile to have multiple grids in my scene?
or does that not work?
This is the beginner coding channel. Maybe try moving your message to #💻┃unity-talk
Why use structs vs classes? I have some classes I use to save data that I think I could easily change into structs but idk if it's worth changing them all if it causes unforeseen issues
classes are "alive" where-as structs are not. Comes with a bunch of implications and potential pros and cons that include structs never being null, optimization considerations and many other things
Don't feel like you have to convert stuff just for the sake of thinking it's "better". Usually it's fine to have something as a class
Usually if I just have a tiny group of data with no functions or etc. I'll go with a struct
RaycastHit is a good example of that (doesn't really do anything it just has a contextually relevant assortment of information)
I mainly use structs as PODs (Plain Old Data) nowadays or if you're wanting an explicit value type rather than a reference type (there are some minor constraints as well).. otherwise nav got the link that I was going to post.
ref vs value type is especially important when doing stuff over the wire , say netcode etc.
Hey! I don't know if this is the right channel, but I'm really struggling with this. (In isometric pixel art) I have a png of the layer in which my water is going to be on, and I want to apply a noise texture on top of it. Only thing is, I can't figure out for the life of me how to go about this. The water shape is not a square, and the only way I could get the noise texture to show up was on a UI image, which I couldn't figure out how to change the shape of..? So how should I do this? Thanks!
You probably want a sprite mask that has the same shape as the water, and the noise can be a sprite that is masked by it
thanks all. if I'm reading this right, a struct might be a good fit for a lot of it since most of the data is simply used once for instantiation once the game loads and shouldn't need allocated to the heap or altered in anyway, just used for instantiation and discarded. However, the line "It logically represents a single value, similar to primitive types (int, double, etc.)." makes me think I should not use a struct since my class stores more than one value. Would the below class work well as a struct for example?
{
public int prefabID;
public Vector3 position;
public int currentHP;
public EnemySaveData(int prefabID, Vector3 position, int currentHP)
{
this.prefabID = prefabID;
this.position = position;
this.currentHP = currentHP;
}
}```
the struct represents a single, primitive-like value, that doesn't mean the struct can't contain references to reference-esque values (though in this case your not doing that anyway)
savedata is a very common usecase for structs yes
Vector3 as struct makes sense
Mathf. not so much , seems more fit for a class but who knows why they chose that
thanks everyone!
really general question, why would i initialize a variable with [SerializeField] private instead of just declaring it as public?
wouldn't the only difference be that i can't edit it from another script? if that's the case, why wouldn't i want the freedom to do so if i needed to like by default?
protecting yourself from your future self
or if working with teams, other ppl not assigning things that shouldnt be assigned in that way
if you have a public variable and you modify it , do you really know that value was changed? Instead it would be better if its just private and modified with a method, this way there you can put things like events or any sort of thing that can say "hey I changed a value here for this"
for enemy save data in particular, id probably keep it as a class just because it might grow if you ever want to save more than just this. It is already more than the recommended 16 bytes.
Another thing to think about in context to a save system, this class can be null. a struct cannot (excluding nullable). If you have a save system trying to load a struct but there is no data, you have to declare another way to say that no data was found. In this case you'd have a struct that contains the default ints and vector3. this isn't a problem really but something to think about since you'd likely want to separate how structs and classes are returned
okay so it's just to keep it private from other scripts for like organizational purposes kind of?
If something is public the assumption is that if a stranger touches it, the code is designed in mind to account for that
if your GameManager has a public reference to your Player and some random script sets that to null, does that break your game?
not organizational (in a way I suppose so) more like access control from yourself and other devs
okay okay that makes sense thanks
Hello I'm very new to unity and this server (so I oplogise if it's not the right chanle) but can someone help me? I have no idea why this is happening
I started unity 3 days ago
and this def not a code question..
what are we even looking at ?
The gizmo handles move with the mouse
Is it like a setting that I accidentally set on
possibily.. looks like its stuck in some sort of surface snapping or something
you tried just restarting unity or something?
Yes
I can do it again tho
thank you!
I'm a bit lost bc can't understand why this code throwing null reference exception when i'm trying to collect 2nd item no matter of his settings. I've tried to delete picked item data from slot and successfully collected 2nd item but then i will get same error on 3rd item. I just don't understand what's been lost and why
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is there a setting to always have the camera visible in the unity editor? When I select the camera I get a green outline of the rendered screen, but when I select another object it disappears.
I think it's been visible always earlier, so I probably accidentally some setting 😐
whenever i try to learn something new in unity i usually get the grasp of it, but when it comes to math i cant understand it for the life of me, is there anything i can do to improve like this maybe a side project or something im still a beginner kinda
add logs and find out what specifically is null rather than guessing
im sure you are aware that if you want to get better at the math, you need to practice it. Google what you dont know, find tutorials that explain it simply, practice it in a small project if you wish.
Guess i've found it, for some reasons it doesn't iterate over slots, thank you
Well, i'm a moron. It didn't iterated bc i've added only 1 slot to array...
How to render SpriteRenderer GameObjects in SceneView via Editor Window?
Hi! I'm working on an Editor Window that previews prefabs in the SceneView. I already have this working for GameObjects with SkinnedMeshRenderer by extracting the mesh and using Graphics.DrawMesh in SceneView.duringSceneGui.
// This works for SkinnedMeshRenderer
void OnSceneGUI(SceneView sceneView)
{
var mesh = skinnedMeshRenderer.sharedMesh;
Graphics.DrawMesh(mesh, matrix, skinnedMeshRenderer.sharedMaterial, 0, sceneView.camera);
}
However, I'm stuck on how to achieve the same result for GameObjects with SpriteRenderer. I need to render sprites from prefabs directly into the SceneView through my Editor Window.
Context: Unity 6000.0.52f1
as bawsi said it's kinda just a matter of practice
but math is a really broad topic, even just math relevant to gamedev/programming
is there a specific topic or field you're struggling with? we could maybe point to more specific resources if you get more specific with your question
I’m honestly not sure what the specific topic is, but it’s mostly when it comes to equations involving vectors if that helps
string tilemapSortingLayer = tilemapRenderer.sortingLayerName;
int tilemapSortingOrder = tilemapRenderer.sortingOrder;
tower.GetComponent<SpriteRenderer>().sortingLayerName = tilemapSortingLayer;
tower.GetComponent<SpriteRenderer>().sortingOrder = tilemapSortingOrder;
why is this code instead of setting things correcty why is the tilemap sorting order -1200
original tilemap's renderer sorting order is 0
TOWER FINAL SORTING INFO - Layer: 'Background', Order: 0
UnityEngine.Debug:Log (object)
i even got debug log of the value of tower component but somehow it was set back to -1200
Its either you setting this or something else
also doing GetComponent() twice is wasteful
How do you serialize a list of references to objects without causing an "invisible" prefab override?
For example in a use-case like this:
public class Foo : MonoBehaviour
{
//If Foo is attached to an object and this list contains references in the scene that are not part of the prefab, it will cause an override. How to fix cleanly?
[SerializeField, HideInInspector] private List<GameObject> gameObjects = new();
private void OnValidate()
{
//Expensive search function to update and assign gameobjects based on the search function
}
}
hello iam new in unity and i have a simple problem that i cant move left and write although my script is true
using UnityEngine;
public class moveLR : MonoBehaviour
{
public float move;
// 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()
{
move= Input.GetAxis("Horizontal");
transform.position += new Vector3(move,0f,0f);
}
}
If this is not changing the position of your transform in the inspector, have you checked which input system are you using @rugged coyote? If you're using the new input system than Input.GetAxis("Horizontal") will not work
Also did you make sure move is not 0?
what do you mean by "invisible prefab override"? What you have is already correct for a serialized game object list
gotcha ty
Either using Debug logs or a debugger you should double check what you are assigning
If it references an object that exists outside of the prefab it cannot serialize it as part of the prefab, thus being shown as an override on a prefab instance. I am referring to this window:
move should i change it?
If it is 0, it will not move
Ah well this just isn't possible but its not something that can be applied correctly anyway. Does it result in entry in the overrides panel with no visible changes then?
Yup basically
what do you think tris?
I was wondering what would be a clean way of fixing this since for our team the blue line indicating overrides is something we try to actively avoid when possible in our scene.
Perhaps a different design that does not require the prefab instance to have a serialized references to scene objects?
e.g use other component that spawns + initializes them with the references needed.
Ignore what I said about it having to not be 0 haha my brain fried for a second
you actively are overriding the prefab though by adding different objects into the list
I was thinking I could move the search for the objects into Awake but that would impact the startup performance of the scene
have you added logs to make sure that the code is actually running without errors?
well you can offload the serialised field to something else so its still "pre computed"
there is a lot of new terms i dont get sorry
well unless you actually ask about specific things then i won't know what you don't know
but i thing my code is true
Either way its not easy to overcome. I think even a new component thats hidden with hide flags would cause the same "prefab changed" issue
are you getting any warnings/errors in the console?
no
Ah right I could try and see if hideflags works
how have you actually confirmed it
i dont get any error
show the console then during play mode
Your code is fine. I tested it in Unity 6. What is it attached to?
i have an icy surface that i want to use to apply a slippery effect on players/enemies
the player can wear something to become immune to it and can also apply something to the ground to turn it into ice
does it make more sense to have the effect be written in the player's movement checking for the ground or for the ground to apply it to the player/enemy
i have one day struggling with moving right and left i feel like iam veryy stupid
show your console during play mode.
when i click on play botton i cant move left and right
show your console during play mode
look at that, errors!
my first time seeing that
you're trying to use the input class but unity 6 is set to use inputsystem by default so you need to change that
as the error says
then it's your first time looking at your console. unity 6.1 defaults to using the input system exclusively, if you want to use the input manager (with the Input class) then you need to change the active input handling like the error says
just vector math in general? any specific dots/crosses?
oh 6.0 is still defaulted to old/both?
as far as i know, yeah. unless they changed it in some patch version
i haven't been using unity 6 so i mustve dropped the .1 in my mind somewhere along the way
breaking changes in a minor version....
beside that, you will have to use some physics based movement to prevent collision issues later, rn you are just changing the transform position
well i guess it technically doesn't break existing projects lol
not really breaking changes? it's just a default setting
no nothing specific like that! mostly just vector math yeah
yes i sent another message after that one
Yup you are right about the hideflags thing not working. Which makes sense. In terms of "offload the serialised field to something else", what where you imagining? I guess through code I could create a gameobject in the scene that contains that list dynamically and has it serialized, and then use hideflags so the user can't see it.
Yea if its something that say many enemy instances need then it probably makes better sense for 1 script to contain this and it can pass on this data on Awake/ custom Init
I was thinking of using a scriptableobject but realized that I wanted to do this during edit time so I figured having references to objects in a scene would not make sense for an SO
Ye I see. Thank you for the suggestion! A shame there isn't an easier way to solve it
It also wouldn't be possible for a SO to reference scene objects at edit time, you'd have to get the references at runtime which is also the thing you are already trying to avoid
That's what I am saying
"not make sense" is not the same as "not possible" so that was not clear
My bad
if your objects have some kind of unique id then that could allow for out of scene referencing but otherwise yea needs to be in scene to be done correctly this way
You can do dodgy shit with scriptableobjects pointing to assumed references like singletons
Ye I rather not haha
I actually don't need out of scene references. I just hoped to be able to store data inside of the prefab instance without triggering the override UI. But it makes sense that I can't do that. My use case is just a really simple script attached to a particle system that checks for colliders in the scene and then loads those references to triggers list of the particle system
I was trying to implement a dash mechanic and it works until we try anything related to the Y axes, more specifically if we try to jump and dash at the same time (and hold jump) it seems like the addForce (from the jump) is still applying during the dash, but it can be something related to Input system, where i check the direction using de vertical system input, I really dont know and i know my code is a mess i really need to clear it
!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/
📃 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.
I assume rb.AddForce inside of the jump input if statement is a mistake? Since you're adding your existing x velocity but you probably want to do just new Vector2(0, jumpForce)
perhaps you haven't thought about/been told about visualizing/understanding the vectors in your mind?
vectors can represent positions or directions, so what exactly the full expression represents depends on what the operands represent
Which class? Reference in what context?
It's an internal class.
can they just not tho like 😭
What are you trying to accomplish
You can do it in a TMP_Dropdown subclass, as one option
Another option is attaching a custom script to the template object and having it change the text color based on some criteria
ohh does it just straight up instansiate that?
The OptionData for the TMP_Dropdown supports a color.
thought it was manually copying over options for some reason
want a bit more control
Or just use Transform.GetChild etc and manually find it
i'd probably figure out how to publicise TMP before that option haha, thanks for the suggestions though
will look into just adding a component if its instantiating the lot
its not exatly that but u made me realized that in the jump if statement if im on the air the game thinks i jumped and will activate the jump code anyways even if i did not pressed the jump input, so thanks
i have to update my unity api level 32 to 36 i have installed 33 34 35 36 versions in android studios and copy pasted them in unity sdk platforms but when i try to build the game it show to update the android gradle verson
Shouldn't the down input only be called on the first frame the button is down and before the player can press the jump button again should IsGrounded not already be false by then?
oh yeah
im trying to instantiate a bullet which then uses the bullet script to move towards the player, but it says it cant get the reference, not sure what im doing wrong
{
timeSinceLastShot += Time.deltaTime;
Vector2 direction = (player.transform.position - transform.position).normalized;
transform.up = direction;
if (timeSinceLastShot >= shotCooldown)
{
timeSinceLastShot = 0f;
Collider2D[] collider = Physics2D.OverlapCircleAll(transform.position, 15f);
foreach (Collider2D collider2D in collider)
{
if (collider2D.CompareTag("Player") && lastPlayerPosition == null)
{
lastPlayerPosition = collider2D.transform.position;
}
}
GameObject bullet = Instantiate(bulletToShoot, transform.position, transform.rotation);
bulletBehaviour = bullet.GetComponent<BulletBehaviour>();
bulletBehaviour.MoveToPlayer((Vector2)lastPlayerPosition, damage, speed);
}
}```
Show the exact error message and which line it points to
bulletBehaviour = bullet.GetComponent<BulletBehaviour>(); points to this line here, the other lines are coming from this function im pretty sure
yh
no that's not right
it's saying the error is inside MoveToPlayer
at BulletBehaviour line 27
you're looking at the wrong lines
clicking that blue text will take you to the actual line of code with the problem
{
Vector2 shotDirection = (_playerPosition - (Vector2)transform.position).normalized;
rb.velocity = shotDirection * _speed;
damageToDeal = _damage;
}```
line 27 is
```rb.velocity = shotDirection * _speed;```
but ive gotten the reference of the rigidbody
in start im doing rb = getcomponent<rigidbody2d>();
don't retype code, copy it over directly
{
rb = GetComponent<Rigidbody2D>();
}```
anyways, does the object in question have a rigidbody2d then
yes
how do i make a scroll rect not interactable but its scrollbars interactable??
is bulletToShoot deactivated or the BulletBehaviour disabled?
cause if i change
scrollRect.horizontal = false;
scrollRect.vertical = false;
then after refresh the scrollbars dont work anymore
(also btw you can type bulletToShoot as BulletBehaviour directly instead of GameObject, so you don't have to do the GetComponent afterwards)
theyre both enabled
show your bulletToShoot/bullet's inspector
and this is the prefab you've set as the bulletToShoot?
sanity check - make sure you've saved and recompiled
everything is saved
try putting a log in BulletBehaviour.Start to check what you get from the GetComponent
for the rigidbody?
yeah
...and you aren't getting the error..?
no i still am
before this message?
...i thought Start ran before Instantiate completed, wtf
i think the null reference maybe coming from this script because of the shotdirection
since that uses the _playerposition
which comes from the shoot function
could i send the whole code of both scripts
yeah, use !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/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
a powerful website for storing and sharing text and code snippets. completely free and open source.
anyone?
That's your issue!
Investigate your code and inspector
Are you assigning components with drag and drop method or manually through code?
Through code
Show me your code where the error is occuring
A tool for sharing your source code with the world!
In here
if possible
The whole script
I already sent it https://paste.myst.rs/h67ec6hn
a powerful website for storing and sharing text and code snippets. completely free and open source.
oh ok
In line 27 in bullet behaviour
If i wanted to print a message to correspond with certain event in the update log how would I do it without the message being printed hundreds of times every second cuz u can't rly multiply a print by delta time
27 is an empty line
Check the blue texts
You're calling MoveToPlayer before Start gets a chance to run
So the Rigidbody2D reference is null
Those more knowledgeable than I:
Is an Event Bus Singleton bad design?
Take a situation. My room may or may not have traps. Each trap does a unique thing to the player up to and including triggering death, to companion damage, or even monsters to appear.
This room may or may not have some or all traps. Is it cleaner to use an event bus to decouple dependencies? Each interested entity subscribes via the bus, and the traps invoke their mayhem via the bus, or should each interested entity seek out in the scene / level what they are interested in at load?
Use Awake instead of Start for that kind of initialization
Alright I'll try in a sec
Why would you need an event bus? Wouldn't the traps be using physics callbacks to run? It's not clear to me what the event bus is adding
so does Start run with Instantiate or not..?
there was another question where it seemed to run before Instantiate finished
Instantiate will call Awake before it returns. Start will happen before the next Update loop.
(Also assuming the gameobject is enabled)
the kernel can access the values up here properly right?
its really seeming like the only valid values are the ones in function parameters
Hmm. Good point.
ok i figured it out
you cant set it in shader code
has to be set here
im guessing they default to 0.0 then
what are you even doing bro
learning
[numthreads]???
huh
ComputeShaders are well above the pay grade of most of the people posting in #💻┃code-beginner
