#💻┃code-beginner
1 messages · Page 321 of 1
Most professional programmers can't even make scaleable code
All of it ran on the first try and worked, connected from unity to node on the host machine and printed the logs correct. No errors
exactly, it can run basic checks on its own code but not actual systems connected together
It's not just a process of writing, it's a process of documenting, training, and refactoring that a LLM simply is not designed to do
at least github copilot type of extensions, train on your own code
but those are cute fluff
Even if you buy into the LLM hype and don't assume it's just copy-pasting snippets it stole from the questions on StackOverflow, an LLM is not a knowledge base. If even one hallucination makes it into your documentation, every single bit of knowledge added after is potentially tainted and would need to be thrown out and rewritten
Theres a right way to use and ask for things with gpt. Ive learned to describe well what you need and to treat it like its capable. It ends up giving very great code that is totally understandable and commented. If you do not like what it gave you, just ask it to rewrite the previous script using a different method and it will
"Will AI replace my coding job"
Future Coding Jobs:
Must go through thousands lines of code to fix AI code
I do not expect ai to write everything, I expect it to give a working script that is easily something to learn from
You're better off tossing a coin
And then the next time you ask it about a different thing it has zero idea what it's already done and has no way of making interoperable systems
Because it does not store that information anywhere
Give it a proper try
It literally cannot
You make it seems like a i tried it once..and said Ok its broke
can someon help
gpt learns from your chat history and changes the way it treats you
I still use it to this day, just not for coding takss..
Has anyone watched this tutorial an knowes if it also applies too Unity?
This course will give you a full introduction into all of the core concepts in C# (aka C Sharp). Follow along with the course and you'll be a C# programmer in no time!
⭐️ Contents ⭐️
⌨️ (0:00:00) Introduction
⌨️ (0:01:18) Installation & Setup
⌨️ (0:05:03) Drawing a Shape
⌨️ (0:17:23) Variables
⌨️ (0:30:06) Data Types
⌨️ (0:37:17) Working With S...
at most maybe writing boilerplates
but I already know what to look for in that
did you read what it said?
yes but i have attack animations
It really cannot. Any sense of it "remembering" you is pure pareidolia
Definitely not. Unity would've been mentioned otherwise
try it
You're saying your prompting skills will magically fix a tool not meant for coding..
C# is C#, of course it applies to Unity
It's programmed to pretend like it remembers you
okay, but what about an Attack parameter on the animator controller?
because that is what you are trying to set
its quite brilliant at writing code if you ask correctly
teach me how to "ask correctly" then
the problem is that i dont know what animator controller
They mean whether it teaches Unity directly
because you created a new chat, intentionally erasing your history
you still don't get it do you. LLM's cannot write code because they literally do not know what code is or how to apply logic
The questions apart from the current chat aren't saved.
All right so just make an entire game and web server database without ever closing the tab or shutting of your computer
THE MACHINES ARE COMING
Yes that is exactly my point
Does anyone know how to make a good looking script because I’m pretty new to coding and I was able to make a walking script for the player but I don’t really know how to make a script for the player to look around?
"goodlooking" script is a scrip that works xD
Which is a awesome thing, because in one chat you may want to talk all about unity, in one chat you may want to talk all about food, in separate chats it learns that topic and about you so it can better help in that field
I think he meant good, looking
check the documentation pinned in #🏃┃animation to learn how to use the animator
Ya
yeah ik just being a smart ass
Oh
there are so many online
did you look around?
best you follow a proper tutorial that covers both, or better yet build your own
...which also means that attempting to make a large program is going to mean your snippets have absolutely no consistency together since the previous ones aren't remembered. Did you lose track of the conversation?
Are you ChatGPT
almost
OK
You can copy paste your script and say "This is what I have now, my next question will be about that code"
So just open a tab, paste 4,000 files of code and say "hey man can you fix this"
basically, not a problem. you dont paste a file, you paste the code straight into the chat and type your prompt at the end. If you want to upload actual files, thats gpt4 lol
So now you're manually opening 4,000 files and pasting them into one giant text document that you can then paste in as plain text. That's worse, you know. You do know that's worse, right?
this reminds me of nam and this is like the new recruit coming in with the fresh gear after the academy
My use is when I actually am lost on something I paste my code into gpt and ask it how I might add a feature into this script, and it sends back that feature. This example is great as a learning tool
Learn! not product
This whole thing was about the concept of writing "scaleable code" in ChatGPT. You're moving the goalposts
Scaleable means it needs to know everything that came before it in order to ensure everything is consistent with existing documentation and standards and that cannot be done with a chatbot that has no working memory or presence of thought
Everything requires learning. For unity, quite some time. Im trying to say that its great to have a tool such as gpt which can show you awesome samples
Which is not what we are talking about
Every time I bring up a reason why it doesn't work for the thing we are talking about you bring up "But it works for this other unrelated thing!"
That's not the conversation right now
you wouldnt want it to be scalable, youd want it to teach you everything about a topic and then you can easily write stuff yourself
Here's another thing a chat bot can't do: Stay the fuck on topic
Seems you may not have learned how to use the chat rooms in it. you could try googling how to use the ai
Most people also cannot
or saying we simply don't know how to ask it, to get good results? thats mental gymnastics
Christ on a cracker it's a fucking chat bot it's not a goddamn mystery box
I've written LLMs. I know how they fucking work
They can not do this sort of high level project management
Programming is not hard because of typing the functions. It can help you do the literal easiest and most trivial parts of programming and is absolutely worthless to do anything difficult
Then maybe this is a good tool to help, if you are ever lost. A lot of tutorials online are not very great, but ive found that gpt is able to clean it up
I bet they never used a Vector database before either
they have no clue how results get composed
ChatGPT is, at best, an intern who can't even get you coffee
Programming is 90% documentation and meetings. Typing the lines into a text document is a pittance of the job.
im sure it could give you great suggestions on how to obtain coffee.
Youtube and google cant give you coffee...
by that logic youtube and google can do the same on "suggestion how to obtain"
Let's not get sidetracked here
Therefor you have multiple choices on learning tools.
At no point have I been talking about learning tools
Yet you continue to act as if I was
This started by connecting database in Unity via Node
who said anything about learning
Well you made it seem as if it were completely useless. So I wanted to provide a little bit of perspective. I dont mean to be way off topic, but just wanted to say that its a neat tool and its wonderful that it is capable of providing code.
Youtube and google have been long used, but theres quite a lot of wrong information. Either way, its all about learning
just a reminder , also yes this is wayy offtopic at this point. I said my peace , you use whatever you think is good for you
Classic
Sparklez using it too much xD
"Hey I was just typing your symptoms into the computer here and it says you might have 'Network Connectivity Problems'"
All I asked it to do was add a break; statement into a for loop
Sorry if I misunderstood. To me it is great because I do not know much about backend, but if you dont like it thats ok. However, you should not call it useless, it is very helpful when learning.
No one said it was useless though ? at least me personally, said the code isnt scalable. Maybe lookup what scalable code/ systems means
@wicked cairn This is #💻┃code-beginner don't bring up ChatGPT here at all. And this #💻┃code-beginner message argument is completely pointless because AI chat is a closed box and publicly posted solutions can be curated by commenters.
Ok. I wont again. There are a lot of fair points in all directions. I see public posts can be helpful sometimes but always arguments on whos code is better, seen that on stackoverflow and stuff. Unity takes a lot of learning no matter how advanced you are, so I wanted to put it out there another tool that may be a option.
When i start the game this sprite appear but i dont select that sprite to appear there
sounds like your code or your animator are populating it
animator ?
what do you mean
I see you have an animator, that typically swaps sprites for animation.
unless its code you have like Praetor mentioned
if (currentHP <= 0)
{
return;
currentBattleState = BattleState.GameOver;
gameOverPanel.SetActive(true);
gameOverText.gameObject.SetActive(true);
} does return execute code underneath once even if its in update?
it wont no
cool thanks
it returns out of the whole function
wasnt 100% sure
You'll get a warning also given that your code editor is configured. On the next line after return;:
Unreachable code detected
Which is pretty explicit
Yh it is grey out. but just wanted to 100% confirm this
it grays it out a bit yea
oh wow Rider grays it out completly
Based on your function name and comment by it that you have not gotten the second delay yet, you can research "unity Coroutines" it works with float delays
yh do others not then
it was working fine, i was just pressing the key in the scene window instead of the game 😂
have used jetbrains for years .
VS just makes the color more grayish
but still keeps the colors
oh i would find that hard to spot
yeah prob bad for those who are not sensitive to color changes :p
oh what theme is this
cant win at every thing
There is no specific theme, I just changed my own colors in VS
looks cool
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollower : MonoBehaviour
{
public GameObject playerPrefab;
private Transform playerTransform;
public int speed;
private void Start()
{
// Find the player's transform
playerTransform = playerPrefab.transform;
}
private void Update()
{
playerTransform = playerPrefab.transform;
FollowPlayer();
}
private void FollowPlayer()
{
// Calculate the direction from the enemy to the player
Vector3 directionToPlayer = playerTransform.position - transform.position;
// Rotate the enemy to face the player
transform.rotation = Quaternion.LookRotation(directionToPlayer);
// Move the enemy towards the player
transform.position += transform.forward * Time.deltaTime * speed;
}
}
this is the font I use
https://www.jetbrains.com/lp/mono/
funny enough its Jetbrains made it 😛
the Player is a prefab btw
is there a question here?
ye the code no worky
it only goes to the players spawn origin rather than the location every frame
@wintry quarry here you go
i was thinking it wasnt updating position possibly
It's doing exactly what you told it to do!
i need to set position to the clone?
how would i do that if it hasnt spawned when it starts...?
No you need the enemy to refer to the clone
im sorry im like really new
When the enemy spawns you need the code to grab the players object at runtime to grab its runtime location
You just pass the reference on your code for the enemy spawner
The reference you put is to a prefab in the Assets folder, not the one in the game
yeah but not the object Cloned from it
when you spawn enemy, pass the Player
so i need it in the enemy spawner script?
yea dont u have one that spawns enemies?
i do
so in there reference the player that was spawned
using UnityEngine;
public class ZombieSpawner : MonoBehaviour
{
//Defines All needed for script to run
public GameObject prefab;
public Transform spawn1;
public Transform spawn2;
public Transform spawn3;
public Transform spawn4;
private void Start()
{
StartCoroutine(SpawnPrefab());
}
private IEnumerator SpawnPrefab()
{
while (true)
{
SpawnPrefabAt(spawn1.position);
SpawnPrefabAt(spawn2.position);
SpawnPrefabAt(spawn3.position);
SpawnPrefabAt(spawn4.position);
yield return new WaitForSeconds(30f);
}
}
private void SpawnPrefabAt(Vector3 position)
{
Instantiate(prefab, position, Quaternion.identity);
}
}
so i can use the public GameObject Player:
yea but you drag the one spawned in scene, not the prefab again
so i would have to do that everytime i hit play?
or is there a way for it to happen automatically
Player = GameObject.FindGameObjectWithTag("Player"); on start. it would be something like this
I SEE
if your player is spawned at runtime you need a method that finds it
i have a player tag
void Start()
{
playerPrefab = GameObject.FindGameObjectWithTag("Player");
if (playerPrefab == null)
{
Debug.LogError("Couldnt find it");
return;
}
playerTransform = playerPrefab.transform;
}
```in this one
the if statement is missing a return
my issue was that i did not reference the Player clone i referenced the prefab, prefab doesnt spawn in a clone of it does
true sorry, was writing trying to read his code at the same time
if its Null assigning a null to a null is pointless
Prefabs are not objects
they are just blueprints to how gameobject will be constructed
so it couldnt find an object
prefab is only a gameobject once its in the scene
and it was like well just go straight since there is no person to lock onto
Prefabs are definitely objects
Actually a prefab is always a game object. It just doesn't actually exist in the scene until you spawn it
and they definitely are GameObjects
And they have a position
whatever position is set in the prefab
nave is the one who said its not. but in this case I meant that hes trying to grab a gameobject at runtime
oh myb then
never really thought of them as gameobjects
makes sense though they do have position
It's weird because they are GameObjects but they also don't exist
Schrödinger's Thing
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollower : MonoBehaviour
{
private GameObject Player = GameObject.FindGameObjectWithTag("Player");
private Transform playerTransform;
public int speed;
void Start()
{
if (Player == null)
{
Debug.LogError("Couldnt find it");
return;
}
playerTransform = Player.transform;
}
private void Update()
{
playerTransform = Player.transform;
FollowPlayer();
}
private void FollowPlayer()
{
// Calculate the direction from the enemy to the player
Vector3 directionToPlayer = playerTransform.position - transform.position;
// Rotate the enemy to face the player
transform.rotation = Quaternion.LookRotation(directionToPlayer);
// Move the enemy towards the player
transform.position += transform.forward * Time.deltaTime * speed;
}
}
so this is what i have now
oh god no..
this is compile error
actually it didnt error on compile
Can't use Find outside a function
i see
You can't run a method in initializer
Read the code I sent again lol!
dont just blindly copy code, you have to understand why you need the code you need
it does exist tho in your scene as long as you have a player object with the tag Player
Assuming that Start function runs AFTER player prefab was spawned
okay so if i copy that to the code it says tjos
otherwise ur back at square one
What is playerPrefab
should configure ur IDE first
in this case it was defined as the playerPrefab earlier
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
but i took it out perhaps if i readd the definition
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollower : MonoBehaviour
{
private GameObject playerPrefab;
private Transform playerTransform;
public int speed;
void Start()
{
playerPrefab = GameObject.FindGameObjectWithTag("Player");
if (playerPrefab == null)
{
Debug.LogError("Couldnt find it");
return;
}
playerTransform = playerPrefab.transform;
}
private void Update()
{
playerTransform = Player.transform;
FollowPlayer();
}
private void FollowPlayer()
{
// Calculate the direction from the enemy to the player
Vector3 directionToPlayer = playerTransform.position - transform.position;
// Rotate the enemy to face the player
transform.rotation = Quaternion.LookRotation(directionToPlayer);
// Move the enemy towards the player
transform.position += transform.forward * Time.deltaTime * speed;
}
}
```Should be like this
configure ur IDE first
Is playerPrefab a prefab or an object in the scene?
whats an ide...
in the scene
It's named prefab but you're getting a scene object
Your code editor
Then why is it called playerPrefab
they are instantiating the prefab so i called it prefab
they can name it whatever they want
okay sparklez it wokrs now
but id like to see if i understand what i did wrong earlier
so, in short i referenced a prefab which isnt ing, so we defined the prefab instead of the prefab as the gameobject that gets spawned in
and from there my code runs normal
oh
and it finds an object with the tag Player and goes to that
its like a gameobject ready to be spawned in, so whatever position it has its whatever it was when you created it
in a brief explanation, stuff like public GameObject stuff will create a empty field. Unless of course its going to use a asset instantiated. What we are trying to do is find a object in your scene that is newly created. In the start() function it will be run for each enemy once they spawn in, thats when they need to find your player active in the scene
you have negative values on ur collider
What about its parent objects
maybe during rintime this happens
OH I SEE
its because i mirrored the original hosue
okay thanks!
how can i mirror the house wihtout just turning the numbers negative?
you shold prototype using Probuilder
using unity cubes is a bitch an a half to make levels
Wdym by mirror? make more of it? click the parent object and press CTRL+D itll dupe the object in the current spot and you can use the arrows to move it
miror across the y axis
so across the street
im making a zombie survival game
hence why zombies move to player
you could Probuilderize the house and use the mirror tool
i have no idea how to use that or where that even is
oh is that why, i thought the player had donuts. (its a joke)
Other than probulder, CTRL+D to dupe it and change the rotation to 180 degree, then use the arrow to move it across the street. If you want to make more of multiple objects at the same time you can hold CTRL and click several objects in the hierarchy to select them
unity also has a FBX exporter package if you want to make the house a whole object
yeah but when i do the dupe thing the door is on the wrong side
i wanted the doors to all be in the center like its just mirrored
the door should be a child of the house. and the house parent is what should be duped
yeah look
and if i flip across the y using 180 it does the same thing where the door is the same spot
i want them to be like this picture
Hm. strange, hard to tell without messing with it. If you are going to model everything in unity, go for the links they sent (probuilder)
can i put the house i made into there?
its just a extra set of tools in unity to model stuff
if you probuilderize it you can use the Probuilder tools on exisiting mesh
so currently i have this version of unity
this is the one my professor told us to download and use
its in package manager, the version is irrelevant
how do i acces package manager?
^ in unity Window -> Package manager
thanks
I would also grab the FBX exporter incase the house needs to be one whole mesh
Ive not heard of that, does that combine cubes??
Looks like his house is made of a ton of cube objects
it is lol
hwo do i add that package?
I dont rememeber if it combines them or you can choose, i think it usually makes its own hirerchy
its not one of the options here
its also in the package manager
could i perhaps do this in a better way and not have this mess in one void?
just pass the SaveData object in the Save method?
wdtm?
Neat. wonder if it truly mesh combines or if its just some data that its together. Will have to try it sometime. 10 years of unity, still always learning something new 🙂 (wrong channel for this chat lol, ill look it up thanks)
also nav i got a question
I usually have a save method that is Generic
i just pass it an object
how can i cahnge the my project into my games name lmao
where is the option for the mirror at
Project Settings -> Player
you have the make the whole house a probuildirezed object (save first)
thank you
Hello, I have a question! I am currently attempting to create a rhythm game esq gameplay loop, I'm currently trying to attempt to work out a way to spawn a projectile object that I have and then have it be destroyed upon being hit by the main player, then for the system to check how close the projectile was to being destroyed to a certain point, would anyone know how to do this ?
I have this scene set up, I want the projectiles to spawn from the enemy and then travel towards the player, then if the player swings at it, it gets destroyed and depending on the timing award a certain amount of points
check the distance to the player at collision event point
how would i make it spawn and fire off in the first place ?
I created this script for the behaviour of the projectile itself
It's best to compare the current song time at time of press with the song time of the note
but I want to create a randomly generated pattern spawning system from the enemy object to the player
The physical objects in the scene are more just for presentation
its not a proper rhythm game, it wont have music in such regard, its meant to be moreso a reaction time game with the scoring system of a rhythm game
Using physics definitely isn't the way to go for a rhythm game
what would be the best method then ?
would it be best to have say like a circle point that indicates the place where youre meant to hit the note, then upon pressing space or something it checks that area for if a note is overlapping ?
physics is mostly when you have shapes, and need to know when shapes are touching, and exactly by how much, what angle, etc
what you are looking for is a system that manages timings of notes, and separately draws a visual representation of said notes/timings to the screen
but no physics is needed, because you do not need to ask if the note and relevant note-hitting-object are touching. You just know based on the timing, and the shapes are just graphics.
in the case of a rhythm game, a physics engine would make everything sooo much more complicated for no reason
As I mentioned already #💻┃code-beginner message
I'm making a game where I'm procedurally generating a terrain. I have it all down and it looks good, but I want to make it so that when the player hovers over the cells, it highlights. To do this, I'm trying to create an empty gameObject on top of each cell to handle those highlights, or any other colors. For debugging purposes, I'm trying to make all the gameObjects over the cells some random material, but they never show up. I'm super confused, all of my terrain is generated great, and the mesh's work, but it doesn't work for these game objects??? Ill send my fucntion in the next message
I also have another function that draws the textures for the terrain, but I don't think that should be a problem when just creating game objects? idk im confused lol pls help
void DrawTerrainMesh(Cell[,] grid) {
Mesh mesh = new Mesh();
List<Vector3> vertices = new List<Vector3>();
List<int> triangles = new List<int>();
List<Vector2> uvs = new List<Vector2>();
// Loop through the grid to generate vertices, triangles, and UVs
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
Cell cell = grid[x, y];
// Check if the cell is not water
if (!cell.isWater) {
// Create vertices for the cell
Vector3 a = new Vector3(x - .5f, 0, y + .5f);
Vector3 b = new Vector3(x + .5f, 0, y + .5f);
Vector3 c = new Vector3(x - .5f, 0, y - .5f);
Vector3 d = new Vector3(x + .5f, 0, y - .5f);
Vector3[] v = new Vector3[] { a, b, c, b, d, c };
// Create UVs for the cell
...
// Add vertices and UVs to lists
...
// Add a tag to the cell GameObject
GameObject cellObject = new GameObject("Cell_" + x + "_" + y);
cellObject.transform.position = new Vector3(x, 0, y); // Adjust position as needed
cellObject.transform.localScale = new Vector3(1f, 1f, 1f);
cellObject.transform.SetParent(transform); // Set the parent to your terrain object
// Add a tag to the cell object
cellObject.tag = "Land";
// Optionally, you can add a collider to the cell object if needed
cellObject.AddComponent<BoxCollider>();
cellObject.AddComponent<MeshRenderer>();
cellObject.GetComponent<MeshRenderer>().material = highlightMaterial;
}
}
}
...
}
which is the part of creating the hover
So I have a seperate script that's doing raytracing to figure out if the mouse is hovering over the game object, but I can't even get the game objects to show up in my game. Like they're all there in the hierarchy, but they dont have a mesh and are invisible
So I'm trying to really understand this game object stuff before I do the hovering
Hi i want make a game of life clone but i really dont see how i can make every square in my grid be editable like when i click on 1 square he become black how can i make that without making 500 gameobject (hope someone understand my request x))
who become black, the square?
Yes
you would just change the sprite/material
you change what you can instead of creating new game objects
Yes i know but they has like 500 square
so what?
For making 500 square how i can without making 500 gameobject
you would make 500 game objects
you would write code to create the objects and place them for you
but if your making any sort of maps, you have to create them
you cant just expect them to be done with a couple objects
This is what i want do
Every square become white when i click on
So i make a code who create all the black square ?
then you just as an example you would have
void OnClick()
{
SpriteRenderer.sprite = newSprite;
}
``` and thats all really it would take i mean if your just changing the sprite, or if you want just colour you can do that also
nothing wrong with them being gameobjects
well if its just one set of squares like a grid and no sort of manual look to it, then you would just use 2 for loops
Yes i know that dont worry the problem is for create the square i just want know if the only way is making a code for create the square
you can manually place them also if you want?
You can use tilemap but then you have less options for individual tiles data
depends what specifically you are trying to do
I gonna check that ty
I did this recently for a virtual guestbook, honestly went with gameobjects. It was easier
Ok but if they are so much gameobject that dont gonna impact the performance ?
500 aint much
wont do much, especially if there isnt a lot of action
have over 1000+
Hey guys i got a rly random/weird problem.
I generated an Object in Unity. Somehow its not visible in the Szene Renderer but it is in the Game.
im pretty sure the problem is here;
The MeshFilter only gets assigned after i start the game
because you do that through code?
i do
so how can it be there before you run the code
Oh ok nice to know thank everyone
oh
I thought if i put it on "Awake" it would load before
awake runs when the game starts
you can make it so you generate with code through the editor while the game isnt running, im not sure how to do that specifically though
you need custom editor stuff i think
yeah doesnt make sense for many projects
but once you start the game you can click the scene view and see it there if that helps
yeah, gonna do it that way i guess
You can also just use a context menu on the generate mesh method code and it will run in editor
omg, thank you!
this lets u run any function via editor right clicking menu
https://docs.unity3d.com/ScriptReference/ContextMenu.html
I use it often to generate lists, autoassign stuff before entering playmode
thank you!
Naughty Attrib [Button()] 😈
for that extra spiceee
the only problem i have w/ it is sometimes I get editor errors.. like Null exceptions
from some hidden/ unseen part of NA
yeah You can create it easily in a few seconds though and make your own attribute
I been meaning to do it but keep forgetting
ya, i been meaning to look at the internals and see whats happening
figure out the attributes part like getting the method reference and combined with GUI.Button = profit :p
ok yeah basically use this, grab script/method then run it thru button in a custom inspector.
oops.. looks like I have some scripts to refactor now
2022+ flex
didn't appear until Unity6
is it supposed to be more efficent or was there just naming change
idk. i only have 1 instance.. so i use the FindAnyObject.. one
says faster so i just believe it
i figured if it was a name change the old one just wouldnt work at all..
Oh if it was just straight renaming yeah lol
lol. ya ur right.. FindFirstObject.. thats basically what FindObject does
just realized that
we cant even see the sauce code so who knows if its just the same thing in a diff name
gotta wait for that next repo dump i guess
Hello guys im working on AR game and since tutorials on youtube are old some things changed, how do i add an AR camera is it included in the XR origin ??
the only way it would be efficient if we finally get new .net anyway lol
Differences relative to name:
FindObjectOfType
FindFirstObjectByType
lol.. that raises even more questions for me
I'd love to do a performance comparison but not even at workstation
This is the coding channel, try asking in #💻┃unity-talk or #🤯┃augmented-reality
Ok thanks man
first part done 😈
Apparently reflection was needed , but luckily unity has class built in of cached values from assembly, for better performance
Verrry nice
i wouldn't know how to do it.. im very novice when it comes to editor scripts
works just by including a namespace?
its basically
[AttributeUsage(AttributeTargets.Method, AllowMultiple =false, Inherited =true),]
public class ButtonAttribute : PropertyAttribute
{
}
```and another class i'm doing
```cs
var extractedMethods = TypeCache.GetMethodsWithAttribute<ButtonAttribute>();
foreach (var m in extractedMethods)```
one problem is TypeCache is UnityEditor class only so I need to figure out how to run that function
like [xxxxx]
now the real question is, will you actually be able to draw anything in the inspector with that without creating a custom inspector for the class
wheres you saying Button means,
that's just how attributes work
yeah like
oh okay.. soo .TextWindowAttribute would equate to [TextWindow] ?
yes
ahh okay gotcha 👍
yeah exactly , trying to figure out how to run custominspector from attribute
i'm not 100% certain since I don't have a lot of experience with custom editors, but i don't think it would actually draw anything for the method with that attribute on it
says in the Docs for PropretyAttribute
A custom attributes can be hooked up with a custom PropertyDrawer class to control how a script variable with that attribute is shown in the Inspector.
but how dammit..
lol
or just variables? how does naughty do this..might have to 👀
cheater!
naughty attributes has a custom inspector for the MonoBehaviour class to handle that rather than using a property drawer
ikr . I just dislike being at mercy of third party volatility
pretty sure naughty attributes still forces the inspector to use imgui instead of uitk
im fine with context menu's
there is something spicy about a physical button ofc
speaking of which I did find a forum post of someone doing it with uitoolkit
i haven't even gotten around to scoping out the tk yet
ah no its this
https://forum.unity.com/threads/how-to-make-attributes-to-draw-a-button-in-a-method-how-to-get-serializedproperty-value.1383171/#post-8711640
ofc in the same forum someone posted the "just use this" solution 😅
https://github.com/madsbangh/EasyButtons
lol.. my discord be glitching 😄

ohh nice
its a less featured NA but a more customizeable Button
button with parameters is kinda nice
oh yea. thats my only complaint about Naughty's button.. which isnt a deal breaker..
b/c i usually use a public variable the Button method will use
and just populate it as i need when testing w/ a button
these are only great to spend the time when you're working with Designers
yea, more of a curiousity than a requirement
how would I make it so that I have the on trigger from a hitbox but I can go through it? I am making a zombies survival 3d game but the zombies can kinda just trap you and insta kill you, I want to avoid that by the zombies allowing players to pass through but still damage them
by marking a collider isTrigger you can pass thru it..
trigger would already do that?
instead of detecting it with OnCollisionEnter.. you just swap over to use OnTriggerEnter
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
on another note
i have a script called BaseZombieScript which is a child of BaseEnemy prefab, I want to reference damage from there what would htat look like?
reference damage from where to where, and what do you mean by "damage"
a variable called damage from the script BaseZombieScript a child of BaseEnemy prefab, to go to the script for my player so that on trigger enter it does damage
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out BaseZombieScript zombieScript))
{
int damageAmount = zombieScript.damage;
Debug.Log("Damage Amount: " + damageAmount);
}
}```
something as so
other is the collider..
TryGet trys to get BaseZombieScript from the collider's gameobject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollower : MonoBehaviour
{
public GameObject playerPrefab;
private Transform playerTransform;
public int speed;
public int health;
public int damage;
void Start()
{
damage = 1;
health = 1;
playerPrefab = GameObject.FindGameObjectWithTag("Player");
if (playerPrefab == null)
{
Debug.LogError("Couldnt find it");
return;
}
playerTransform = playerPrefab.transform;
}
private void Update()
{
FollowPlayer();
HealthCheck();
}
private void FollowPlayer()
{
// Calculate the direction from the enemy to the player
Vector3 directionToPlayer = playerTransform.position - transform.position;
// Rotate the enemy to face the player
transform.rotation = Quaternion.LookRotation(directionToPlayer);
// Move the enemy towards the player
transform.position += transform.forward * Time.deltaTime * speed;
}
private void HealthCheck()
{
if (health <= 0)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Bullet")
{
health -= 1;
Destroy(other.gameObject);
}
}
}
Base Zombie script
damage would be a public int thats accessable
#💻┃code-beginner message i mean
public class PlayerHandler : MonoBehaviour
{
//defines important numbers and such
public int health;
public int ammo;
public GameObject Bullet;
public GameObject BulletSpawn;
private int BulletSpeed;
private float cooldown;
private Rigidbody bulletRigidbody;
public int kills;
public GameObject BaseZombie;
// Start is called before the first frame update
void Start()
{
damage = BaseZombie.GetComponent<damage>();
BulletSpeed = 20;
bulletRigidbody = Bullet.GetComponent<Rigidbody>();
ammo = 100;
kills = 0;
health = 100;
}
// Update is called once per frame
void Update()
{
HealthCheck();
Shooting();
if (bulletRigidbody != null)
{
Vector3 direction = transform.forward;
bulletRigidbody.velocity = direction * BulletSpeed;
}
}
private void GameOver()
{
Debug.Log("You Lost");
}
private void HealthCheck()
{
if (health <= 0)
{
GameOver();
}
}
IEnumerator BulletLifespan(GameObject bullet)
{
yield return new WaitForSeconds(3);
Destroy(bullet);
}
public void Shooting()
{
if (Input.GetMouseButtonDown(0) && (ammo >= 1))
{
ammo--;
GameObject bullet = Instantiate(Bullet, BulletSpawn.transform.position, Quaternion.identity);
Rigidbody rb = bullet.GetComponent<Rigidbody>();
Vector3 direction = transform.forward;
rb.velocity = direction * BulletSpeed;
StartCoroutine(BulletLifespan(bullet));
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Zombie")
{
health -= damage;
Destroy(other.gameObject);
}
}
}
the script i want to reference from
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and you already got the answer
the script i want to reference to
so idk what the code spamming is for
another note.. instead of using other.gameObject.tag == use other.CompareTag("TagBeingUsed")
if (other.gameObject.tag == "Zombie")```
no need to even use a tag here.. if it has a script called `BaseZombieScript` then
```cs
if (other.TryGetComponent(out BaseZombieScript zombieScript))
{
zombieScript.Foo(); // call function
int damageAmount = zombieScript.damageAmount; // get variable
}``` would be plenty good enough..
it would act as a conditional.. (to know if you collided with zombie)
and it would automatically grab the reference to the script (so u can access variables/functions from it)
what is this?
u dont even have a variable defined for that, heres what i notice
- no damage variable declared (unknown source)
- is damage a variable from BaseZombieScript or is damage a script of its own..
- rigidbody gets assigned in start (im assuming with a prefab's rigidbody)
- it should be assigned to the new instance of the bullet after it gets instantiated (like you have now but no need to set it in Start like you have)
i also suspect that your !ide isn't configured.. since you would get errors provided the last script you sent..
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i have in the zombie script a public int called damage
i just wanted to reference that int
then it would be damage = BaseZombie.GetComponent<YourZombieScript>().damage; <-- this would Grab YourZombieScript from the gameobject you assigned to BaseZombie in ur script.. and then access the damage variable... that is if its public
oh so thats how it works
thank you
i was trying to find it out online but it wasnt much help
you dont need to do any of that tho.. you can get the damage variable From the zombie script as soon as you collide with it..
if (other.TryGetComponent(out BaseZombieScript zombieScript))
{
int damageAmount = zombieScript.damage;
health -= damage;
Destroy(zombieScript.gameObject);
}```
then you could remove public GameObject BaseZombie i dont see any reason for that..
is zombieScript the class name?
same thing with ur private Rigidbody bulletRigidbody; you could just access it when you need it (each time u spawn a bullet you need that Exact bullets rigidbody
BaseZombieScript is the type, zombieScript is just the name of the variable you create
GameObject bullet = Instantiate(Bullet, BulletSpawn.transform.position, Quaternion.identity);
Rigidbody rb = bullet.GetComponent<Rigidbody>();```
this is good enough for that..
you really dont know any basics of C# tbh, should follow a tutorial
i agree, no hate.. but the way that script is structured, its bound to give you lots of issues
so basically what i used was this
EnemyFollower enemyFollower = FindObjectOfType<EnemyFollower>();
enemyDamage = enemyFollower.damage;
``` now that i know how to pull the script
and this works
i was just trying to learn how to reference another script
if i wanted to do it simple i could have used a return damage kind of thing
ScriptName referenceName = theObjectYourSearchingIn.GetComponent<ScriptName>();
yeah thats what i figured out when you sent the thing earlier!
GetComponent w/o a prefix would search the gameobject the script ur working in is on
it was a really big help
and the . accesses the prefix so, script.MyVariable; would access MyVariable from the script thats refrenced by the name script
good luck.. referencing scripts and variables is a big hurdle for beginners.. once it starts making sense coding gets alot easier
https://gamedevbeginner.com/how-to-get-a-variable-from-another-script-in-unity-the-right-way/ heres a good resource i go to from time to time
okay thank you!
also i think this was answered earlier but i didnt quite understand, I have this model of a zombie I made and I want to be able to passthrough it but still be able to detect collision
set it the collider to isTrigger in the collider component..
u'll automatically be able to pass thru it (hence what a trigger is)
to detect it.. Instead of OnCollisionEnter like u'd do with a hard collider
its OnTriggerEnter
the rest of the stuff is basically the same
you have to actually mark the collider to be a trigger
not just change the code..
the code is only detecting
i mean
oh
perhaps the parent needs it?
cuz right arm left arm head and torso all have colliders but the basenemy and arms dont
ye look
each collider u want to be a trigger u have to mark every one
okay so i want the arms to be a collider for damage and the torso to be collider for it to take damage from bullets
some useful tips/hints in here about using multiple colliders
probably going to have to use multiple child objects for each collider.. and possibly with tags for each type so u can evaluate what type of collider it is after you collide with it
- Torso Collider
- Limb Collider
just depends on your setup.. and how you are interacting with the colliders.. (raycasts/ collisions/ triggers etc)
should I call rigidbody2d refrences in the start or awake function
Awake <- Set up self
Start <- Set up others
if you're setting up references to Rigidbody2D components that other scripts might depend on, do it in the Awake function to ensure they're initialized early in the object's lifecycle
if its only important to the script itself.. then it wouldn't matter which one you did it in
when i click play my charector i added wont render
i added sprite render
and added my sprite
is it in front of the camera?
when im in scene view i can see my charecetor
sprites usually are
press play and then click the sprite and hover the scene window and press F
it should focus on the object. and you'll be able to see if its off camera for some reaosn
nope, the only thing i can think of.. and usually the case is the sprite is either on the same Z coordinate as the camera.. or its behind the camera..
and then if not.. lowering the camera's clipping plane..
when you focus on the sprite it should atleast show you in the sceneview where it is.. after you press play check both the sprites Z value and the cameras Z value
ok
camera usually uses a -10 z value
as long as ur sprites are > than that u'll be able to see em fine
thx so much
do you know how I can make it so that my gun object from here can move up and down where the player is looking
most times people have controllers that rotate the camera up and down.. Guns can be parented to the Camera.. and it will rotate as well.
so drag the gun parent to the camera?
if not u can write a script that can rotate up and down using the mouse..
you can also raycast from ur camera and get a hit point.. and then have the gun point at that point..
the camera looks up and down fine just the gun doesnt move
if ur camera already rotates.. u can just put the gun object as a child and it will also rotate
nice
ye that worked perfect!
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
if (Input.GetKeyDown("alt"))
{
Cursor.lockState = CursorLockMode.Locked;
}
``` and for this how would i use left alt
just '''leftalt''' or is there a specific name?
i tried alt and it was like nuh uh i have no clue what that is
how do i assign/change the x and y position of a gameobject?
for moving in x and y, do transform.Translate(*xamount*, *yamount*, 0)
for setting it, do transform.position = otherGameObject.transform.position
assign a new Vector3
ok
thats not how you add a new ConstraintSource object
you can either change the keys inside the input manager (settings)
or you can use the exact keycode.. which is https://docs.unity3d.com/ScriptReference/KeyCode.LeftAlt.html
Input.GetKeyDown(Keycode.LeftAlt);
create a new ConstraintSource object
but if i hit escape i have to click the game again to press alt for it to work
when you use a string "likeyouhavenow" its either defined at the top of the script.. or its using a preset in the
new () creates a new object
like Input.GetKeyDown("Fire1") that works b/c its a preset
var constraint = new ConstraintSource()
{
sourceTransform = theTransform,
weight = 1,
};```
thats a built in feature of Unity.. that wouldn't happen in a Built version of the game
ight thanks
i usually use an alternative for Escape until im done working in the editor
back-tick works great
idk if i'm saying this right, but I want to set the tile at a position in a tilemap based on perlin noise(last part is done). I have no idea how to get the tile and set it though
can anyone offer help?
I don't understand how to get use x and y to then get a tile from the tilemap and set it to a different tile based on the value the perlin noise returns for that position
Custom tiles most likely
more research! I can't wait. . .
for changing tiles
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetTile.html
world.SetTile(What do I do here?);
I have this
but the issue is you have to input a tile
and I don't know how to get the tile
wait
you dont have tiles in your project folder?
they are just assets
public Tile tile
you can drag one in the inspector for example
haven't played too much with rule tiles, just scriptabletiles (basically the same tiletype usually)
alright
this blogpost might be able to help you out
https://blog.unity.com/engine-platform/procedural-patterns-you-can-use-with-tilemaps-part-1
When I use List.Count does my count start at 0 for example if I have a list with 5 elements the count is 4 or does it start at 1?
starts at 1
Ok thankyou very much
index start at 0, count start at 1
you can check that with a Debug.Log
or 0 if the list has nothing
Hi does anyone know if there's a way to simulate lag in unity? i want to simulate lag to test how well my game handles it etc, but i can't find anything online about this. is there a simple way to do it in unity? i know there's the frame step but that isn't exactly what i want, does it have to be done in code by limiting the framerate?
Network lag can be be simulated with https://github.com/jagt/clumsy on Windows.
what about just general lag from single player games?
Single player games don't experience "lag"
If you mean a framerate/performance issue, you can use Thread.Sleep
isn't that lag?
how do i use thread.sleep?
You wont really get the results you want by doing this though
thread.sleep will sleep the whole editor iirc
I don't really understand what the point of such an exercise would be
im trying to make a rhythm game and it uses timescale for the beat etc, and im trying to make sure that lag etc doesn't cause it to come out of sync
You mean low framerate
or sorry, "framerate/performance issue"
Use thread.sleep
If you're trying to optimize your game, you should test and profile it on target platform/hardware and use the profiler data to optimize it if needed.
You can use a random range if you wish or put it behind a button press
Or Application.targetFramerate
These are fine ways to test how logic behaves at different framerates, but this isn't a way to test performance in general.
im not trying to test performance in general more how my game handles lag spikes which doesn't always mean the game has bad performance
frame dips*
These are performance issues
The solution is not to have lag spikes in your game.
so if someone decides to suddenly extract a zip bomb mid game it means my game has a performance issue
Hooking Thread.Sleep to input or Random will probably do the job then
when I turn is trigger on my capsule collider for my player to on it sinks through the floor, how can i prevent this
dont make it a trigger
Don't make your collider a trigger
and do you know what trigger even is? or are you just doing things randomly still
it needs to be tho for my player to detect collision with the enemy
It seems you don't understand what a trigger is
A trigger doesn't physically collide with things
That's the point
oh i see
so on collision would work better?
but when i did that earlier my player would get stuck inbetween zombies and not be able to move
it wouldnt "work better", it would make it work
I got bullets with rigidbodys I want to make it so that they dont interact with each other but they interact with everything else
Maybe separate colliders for platforming and for enemy interaction then
turn of the collision between them in the layer matrix
do layer based collision
would using raycast be the better option here?
alright ty
what would that change
for collision between my player and zombies
your still going into your player
Layer based collision detection is what you and @viral creek both need
that will not help
It WILL collider BECAUSE it is not a trigger.
Triggers do not collide physically
OH WAIT I SEE
triggers is for passing through objects
but detecting collisions works great for non passing through
but what if i get trapped between them they just constantly drain hp and theres no way of getting out
been said 3 times already
okay im sorry im like extremely slow
that would make you phase through them
again, OnCollision OnTrigger Raycast, does ABSOLUTELY nothing for the collision
okay
if you disable collisions betwen layers (player/enemy) they wont collide
i understand that
how would i disable the layer collisions
and put them on different layers?
its a 3d game
the physics engin will handle all "overlap events" for all colliders (but the callback depends on the rb/layer)
if i want a bullet (OnCollision) to bounce off a wall do both need rigidbodies or can i remove it from the wall? they both already have colliders
the wall doesnt need it
that doesnt make sense
You need a Rigidbody basically for anything that moves
If it doesn't move, it doesn't need one
my bad, everything is in vector3int
from the moment I saw there was an int version I used it for essentially everything except worldpace transforms
I saw this done one time but forgot how, how would I be able to predefine an animation curve to be Linear?
Does this not work?
ah nvm it does but i still would like to know if I could predefine what type of curve it is
There are no types of curves. The curve is generated from the key frames.
Though there seem to be a static method that provides a linear curve as a shortcut. Check the API docs.
thanks
So I seem to be able to capture the king, but it's not calling the hidden method. do I need to ensure I am calling the king script that inherits from shesspiece or smth?
Hidden method?
if you're doing new on a derived method it's probably breaking polymorphic relations if you're calling it as a less derived type
you need to mark the base class's method(s) as virtual and override the method and call its base implementation if you want that behavior. right now you are hiding the base class's method which means for all intents and purposes it does not exist when interacting with that object as the derived class
@rich adder I did your method and I found that the textures weren't lining up properly. any idea why?
I am kinda messing with the camera of my game now cause I not sure if I am really happy with it just floating on top of the player for a cenital view. So I am trying something more typical 3rd person behind your back. And now I am wondering... how the heck do I make the inputs now relative to the camara position?
I tried mirroring and rotating it and it didn't do anything
Is this just by parenting or how?
wait nevermind it started happening with my other tile as well
Thanks I'll fix that
does anyone know what im doing wrong? trying to get the "elevator" the square thing to detect when its overlapping with object with the despawn tag and its just not working, even though i think i setup everything right, i know it isnt working cause yeah it isnt logging the yousuck string
I see no trigger collider
also no rigidbody
Both are required for OnTrigger messages
hm alright mustve missed that where i found this thank you
Kinematic RB will cause a collision event w/ a regular RB? interesting
yeah, it's the dynamic rb that sends the collision event there
modding discussions are not permitted here
Hey im making a movement physics based and i wonder which is the best at handling movement in general and overall
There is no best, each movement solution eventually hets fined tuned to the specific game it is meant for
grab yourself a kinematic character controller and start developing your own
What do you guys usually use for general use physics movement
I do not know how many ways to move the character using physics
Could you tell me a few that usually used
rigidbody is the full packaged physics controller provided by unity, otherwise you have the character controller (which surprisingly is more common to see in unity's templated projects) which has a few physical component integrations, but gives you more freedom to append your own physics logic to it.
There's also kinematic rigidbody controller which I'd say is similar to the character controller, but more tied to unity's physics system.
they both have different APIs for the most part kinematic rigidbody will still use the related rigidbody methods for movement
And then there's this custom character controller which I've heard good things about:
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
https://hatebin.com/tjdqlcmhvd Hi, this is my weapon script in my game and I want to implement some kind of weaponbobing so it moves up and down when I am walking, can someone please help me with that?
If your weapon sway is working there, why don't you migrate some of that logic over
I tried but the problem was that it just didnt work idk why I could try again tho and then ask I guess that would be proppably smarter 😄
AngleAxis does seem like a good idea here, and you probably want to move it up and down the x axis (tilt)
maybe some z for the roll
yes... I will add some kind of rotation to it too
yep
well I will try and then come back when I am stuck
I think you'd probably want to use slerp here too considering you're working with quaternion rotations
https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
This would also provide constant rotation speed if you prefer that
Er I mean the quaternion method:
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
Hi. So currently my design looks a bit like this:
- Scene.cs are scripts that deal with specific functions inside each scene. (Example, MainMenu.cs PlayAdventureMode() )
- MenuUI.cs / GameplayUI.cs are scripts associated with the game state that handle UI functions. (Example, healthbar changes, button press noises) Main menu has a MenuUI.cs but not a GameplayUI.cs for example.
- AudioManager.cs manages audio sources aka creating, setting values, etc and puts them through AudioMixers.
So currently my AudioManager has a .Play() method which is called in Scene.cs and MenuUI.cs scripts.
Would it be better to have a SoundPlayer.cs script which deals with audio, then those other scripts depend on it?
bawsi you around? I'd like to talk about designing a good client/server interaction that prevents cheating, but is also fast
my currently implementation is pretty slow, we talked about it a bit the other day
how to print list or array or any collections without iterating and concatting any values inside the collection
like calling a toString() and everything is printed nicely
which tostring() isnt working here
impossible, even you own toString() need to iterate the whole collection
you can use debugger or format it by json
Don't get what you mean? You want to print all index of an array without iteration?
lets say List<string> list
list[0] = "Apple"
list[1] = "Orange"
if you ever trying to look up any printing tutorial for unity, u will notice stackoverflow teach you by concatting and iterating the whole collection and then debug log the value out
which is really trobulesome and time wasting
but theres really a way, without having to iterate anything inside the collection, just by calling a function and it does magic
["100-10000","150-15000"]```
Not sure how concatting is required there? Unless you want a message next to it?
As for iteration, yes it needs to happen. You can't just say "hey array, print out the whole thing" to my understanding
or
["Apple","Orange"]```
you can
How then?
you serialize the whole collection into json, unity treats all serialized json stream as string, thats why u can print them all out
There you go, it's a specific unity API. Usually it wouldn't be possible
yeah i just forgot it
Just so you know that isn't printing values, it is parsing the c sharp to json. So it doesn't read any values apart from the written text
its enough, i just want to see what value does the collection has
bump
https://hatebin.com/iqqriyqoyd this is what I come up with but its all wrong I am not sure what to do cus it needs to go up and down not just up so how do I change tha trayectory YK I am just lost
also it needs to have a transform which I dont want to have I want to make it whole code made
can someone help me with this please?
well if someone wants to help me just respond to my message I will be online again in like 3 hours from now THX
Does anyone know why this code returns pretty much the 32 bit integer limit, dropppoint: x: 2147483647 y: -2147483642
private int x;
private int y;
private RectTransform Rect;
void Start()
{
Rect = gameObject.GetComponent<RectTransform>();
x = (int)(transform.position.x / Rect.rect.width) - 1;
y = 6 - (int)((transform.position.y - Rect.rect.height) / Rect.rect.height);
Debug.Log(transform.name + ": x: " + x + " y: " + y);
}
debug what each value is, shouldnt be hard to find the culprit after a few seconds of debugging. Also what you're doing there seems weird, dividing a position by the rect dimensions
it is on multiple objects and i want to get values for a 6 by 12 grid
still, debug what each value is. itll be clear once you see the math being done
it returns 0 for the width and height for some reason
bump, please give me advice if anyone knows
I want to know, if I make some scripts that handle different components of the engine, example: Sounds, UI, Animation, etc... Can I then use events to decouple them?
probably something about the canvas or ui not updating yet
An example is like an event/listener in UI then the Sound and Scene.cs methods subscribe to it
yeah ill just fill it in myself since those values shouldnt change anyways
I dont see why you wouldnt be able to use events to decouple your logic, though it seems like AudioManager is already your highest-level controller, so splitting that further into a "SoundManager" sounds like repeating a lot fo what SoundManager already does
yo guys, what happened to ProGrids in Unity 2024
i just saw this, but im definitely not the best to ask in this. your best bet is probably google or the #archived-networking peeps as i stopped doing multiplayer. I know ngo also has the network profiler, so you can see whats taking awhile to do.
Yep I see your point. I am over engineering it by creating that script I guess. It feels a bit weird that the Audio methods are referenced everywhere though... Do you think it is okay?
Im trying to find out how the whole Grid thing works
does anyone know why I dont got the ProGrids thing on my window panel?
I don't mind revising my design if the event approach is better
this isnt a code question
It really depends on what is the most decoupled and practiced
At some point in your chain, a script is going to need to reference something, I often put those higher level systems into a namespace, it helps for organization, but also gives me a second moment to think "does this script REALLY need this system? If I have to go through the effort of referencing it, that means it depends on this namespace... Does it need to or is it trying to do too much?" - though I dont think in your use case an audio reference would be "doing too much", though I think events do sound like a good idea (maybe a bit bias, as I tend to use events to communicate between a lot of systems like UI and gameplay)
So referring to your first sentence: relying entirely on an event based design is unrealistic?
Not that I intend to do it... Just considering every option
I wouldnt say "unrealistic", events are used in many projects, though at some point youll have to have a class reference something specific, even if you have global events/broadcasters, some script will need to reference those global classes, or pass data/objects through events for another system to respond correctly
Another option you could explore are interfaces, though I find they can be a bit tricky to understand and implement effectively, but it can allow a system to become multiple systems, like a IAudioListener, or a IMenuManager, if your various audio implementations/menus have more-or-less the same code in a different flavor
Could you expand a bit on the Interface solution? Also thank you massively for the help
I use Interface for my gameplay implementation
So it should be easy to understand if you could just expand a bit
Say you had functionality that would be similar in pretty much every menu you make, like public void ToggleUI(bool fadeIn), you could have that in a IMenu interface, and for everything that needs to act like a menu, it can inherit for example MainMenu : MonoBehaviour, IMenu, CharacterSelect : MonoBehaviour, IMenu, etc - some other system can just call IMenu.ToggleUI(true); and have that character, or main menu or whatever fade in, but that same menu could also have IAudioListener if it has common logic with playing audio or subscribing to something audio based, your audio manager could call IAudioListener.Play() without needing to know if its coming from a main menu, a character select page, etc, though in that specific example, it could be overkill compared to an event in your audio manager that other scripts can subscribe/unsubscribe themselves with
Hello was just curious, I'm currently attempting to make a small game where projectiles are fired at a player and the player has to slash to destroy them, I have set up the projectile's behaviour alongside given the player an attack but have no idea how to go about spawning the projectile itself and laso randomising the spawn to say spawn 3 back to back and then maybe like 1 every second, could anyone help?
Thanks!!
hi there, i creating a game, for a school project, and i need help with adding a door, i want to add a door, and when i get close to it, it says " Press E to exit", and if we pressed the game end, i am new using unity, so i dont know how to do that, any help is welcome.
Use google , or youtube "Unity create door" you have some good tutorial
thank youu
in unity, UI will register an event , or listen to an event and call certain functions to do stuffs
onclick is an intrinsic event given , but can you invoke onclick by script, not clicking on the UI?
oh you can, NICE
This projectile sounds like it can easily be a rigidbody with a collider, then spawn it and launch it by either setting velocity or using addforce.
As for spawning them in intervals, you either use update and keep track of a timer or use a coroutine
ive given the collider a rigidbody with a collider
how would i go about spawning them and using addforce? im new to unity so have no idea how to do this
You would make a prefab for the object, then reference that prefab from a script. You can directly reference the rigidbody component from the prefab instead of the GameObject. When you instantiate it, it will return the rigidbody, which you can call the addForce method on
You also dont have to use rigidbody motion, since I see you are directly moving its position.
oh is that not necessary ?
The rigidbody is needed if you want it to have collision with walls and such
okay i see, well currently the only collision it would need to have is with the player or the player's hit
since if it collides with the player the player takes damage
or if its slashed by the players weapon its deleted and adds a score to their score counter
rigidbodies give the projectile physics if u want that too though
makes them more realistic
I'm getting this error but im not too sure what it means, this is the line that it takes me to in the players combat script
This is a common c# error indicating you tried to invoke logic on a variable that is null
So you should take a look at this line and figure out what could be null
Hint: it can only be one thing
the get component ?
How would you figure out if it is?
probably because i copy pasted code from another enemy with the component named Enemy and forgot to change the line of dialogue LOL
Perhaps
am i able to have more than one of those lines ?
One way to figure it out would be logging if component == null https://unity.huh.how/debugging/logging/how-to
One of those lines?
I don't know what you mean
since i have these two that i want the player to be able to hit
but currently my code is only accounting for the enemy ocmponent
If you want to access the enemy component it must be part of the enemy gameobject you use here
I should correct myself, two things can be null here
So please take a step back and start logging #💻┃code-beginner message
Because not only the component can be null, the enemy variable can also be null
This is the very first thing you should be figuring out
im confused where the log goes? just in the line above ?
Yes, definitely before the code or it will not trigger because of the exception
right
im confused exactly what i should be logging though ? since the code works fine when trying to attack the enemy object just not the projectile object
Yes
Note there will be another exception popping up if enemy is null but the whole point is figuring this out anyway
Try Debug.Log(enemy == null)
So the second one is null, which means the call for the component is null
This means the enemy variable you are using doesn't have an Enemy script attached
okay right yes that might be the issue
i dont exactly want it to hav ethe same script though as I want to make adjustments to the enemy's health without changing the current script
ah wait i think i was being stupid this whole time
yeah okay so if I attach the enemy script it should work now
Yeah it always needs that, I'm not sure what you tried to do
Note if the component is optional you can also use GetComponent and then check if it's null
I was trying to create a seperate script using the enemy script's code since they'd have the same properties just altered a little
The exception is only thrown if you actually apply logic to a null variable
right
I'm confused. If you want different properties then why not expose some variables in the inspector to adjust from there?
Does timescale= 0 stop coroutines?
im extremely new to unity so kinda just learning through tutorials and just testing about so im not too certain on what works and what doesnt
Yes, I think it does, but why not try this?
stop wait for second
I see, consider looking up SerializeField at some point and see how you can expose variables in the component inspector
I'm not at a computer right now so I just wanted to ask for when I get back
I have ran into another issue though which is that im no longer getting the error but for some reason it appears as if theres no collision with it
It definitely did because the exception is being thrown
But my guess is that TakeDamage has no effect?
TakeDamage has an effect on the other enemy i was testing out on earlier so if im using the same script should it not function the same ?
idk if im stupid or what but why does does return an empty array? **
Collider[] hitColliders = Physics.OverlapSphere(Vector3.zero, 1000);** scene is set up fully empty with just a default box collider cube at 0,0,0
Well if you suspect it's not called then try the same logging technique, but instead see if it's logs in general to confirm it actually runs
have the cube toggled off , press play.. then enable the cube and see if it's found then. Other than that, we can't tell you because this single line isn't enough information to know what's wrong.
Hey guys, I do have another design question: what is the best way of finding scripts in the scene.
- FindObjectsByType/FindObjectsOfType, for this I have only been using for singletons. Still, I know it is slow and although I used sparingly am aiming for lower-end devices so want to replace it completely.
- GetComponet with SerializeField and drag and drop inspector. This way seems to be the most intended although I run into issues. If there are multiple scripts of many types, it can be confusing to go through all of them and attach relevant scripts
One "solution" to this problem is to use the Drag&DropInspector->SerializeField->GetComponent way but instead attaching all scripts used in the current scene inside a "management" gameobject, then you reference that single script.
Want to hear other's opinions on it, or if you have a video/resource please share it
yep, still doesnt detect, but what more info do you need?
https://unity.huh.how/references
afaik - singletons aren't slow..
the setup and more code..
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh okay coool, so your approach is predominantly serialized references. How do you deal with missing references after changing the reference inside the script though? Also, it relies on the editor's inspector to remember and store the references which I have previously had lots of references lost from minor changes to scripts
figured it our, had a bigger code problem
I wish Unity supported the rename feature in Visual Studio
Because you make a reference and then have to change the name, then you're caught with a bunch of missing reference errors
It could be dependency injection that I'm looking for then
Still run into the inspector problems though. Unless there is a way I'm using the inspector wrong?...
You can also inject dependencies through code, which would just be setting references and/or calling methods with the dependencies/data as parameters.
In your experience, what is your preferred way of referencing? Let's say you have AudioManager and you need to play a sound in PlayerEffects, how would you go about it?
tbh if you find yourself frequently having to rename classes it means you are not designing your systems you are just making them up as you go along and that is what is causing your problems
Yes, you are correct in the fact I do not plan every single field/property in advanced. Although, I do UML diagrams of the design, even then, names change, systems grow. You can't be telling me that the flexibility is not a big advantage
Recently I've been injecting almost everything. I use inspector serialization when available, then drop down to code based injection when needed.
Is your method of dependency injection the same as this
Does the DI prevent the issue with the inspector I am adressing too?
Yes.
Thanks, I'll try it out!
Initializing through code allows you to pass scene references to runtime instantiated objects.
Oh, this shouldn't happen at all. You should be able to rename stuff without things breaking
Wait, how?!
rename the script file in Unity then rename the class name in VS
Hi, chatgbt told me use Rigidbody or CharacterController for zombie movement, but i want ask you which one is better? (i use rigidbody rn)
It should work out of the box. Unity uses IDs stored in .meta files to handle those references.
Make sure your !ide is configured?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Renaming in VS should work fine too
Just tested, it removes the reference 💀
no it wont because the .meta file will not be renamed
Make sure to use the rename functionality
It does. Ctrl+R+R on a class name changes the file name
Oh wow, it actually doesn't seem to work
In Rider when you rename a Unity serialized field it automatically adds [FormerlySerializedAs] which avoids this issue
Oh you meant renaming a variable. Yeah, use the attribute Prae said
So... What is the solution here?... Because the whole point of renaming references is usually to improve readability when refactoring, so if that effort is countered with the time waste of dragging the script back again, what is the solution
I care about performance so to avoid Find() and other similar methods, but I also care about time efficiency as a developer
And yea, you could say "get Rider" but that fixes the issue for a single person in potentially a group of other members
The other members get to manually add the attribute 😉
I think - without question - it's the responsibilty of the developer who does the rename to fix the references afterwards.
If you use the attribute that still can look like a process of:
- Rename (with attribute)
- Reimport/Re-save all assets that have that reference so they get the new serialized name
- Remove the attribute
Rider of course has another useful feature here in that it tells you exactly where in your Unity project serialized fields have saved values
So that makes it easy to track down all the assets that need to change
Sorry if this is sounding more and more like a Rider advertisement
I am hooked. Though I thought it was subscription?
Seems like the most supported IDE
Any student?
Is this the right place to ask about camera problems?
Does it work well with C++?
If it's camera code
And gets significantly cheaper the longer you stay subscribed (to an annual subscription)
Rider is for C#. They have CLion for C++
Rider is for C++ as well
Is it?
CLion for Cmake C++
Oh you're right
RIder for vs soultion C++
so Rider for C++ on windows
Clion for cross platform or mac/linux since its all cmake
No matter what values I set for BoundsX/Y/Z, the camera will still move, but it works for ZoomBounds - https://hatebin.com/ibgwmenuuk
Ugh... Well anyway thanks guys. I'm happy I learned that attirbute exists at least
Also does Ride work well for Unreal
My current Unity instance wasn't handling type renames for whatever reason, but yes, it does work.
@languid spire .meta file is also renamed with the ID intact.
Your code is only clamping position when using the mouse. Not when using wasd
no idea on that part I'm afraid
Yes, variable names do need the attribute when renaming, but type renames can be done as is with the renaming functionality.