#archived-code-general
1 messages · Page 157 of 1
is key remapping doable without the new input system
If I want to pre-calculate the effect that manipulation of a parent object will have upon its child object, how would I do so?
yes, should be a tutorial somewhere on it . . .
Is there a way to hook a debugger onto Unity so I can get a stack trace of my code executing when I hit generate for my procedural terrain? Every time I generate a 100x100 terrain, it takes 15-20 seconds just to execute, and I wanna see what's taking so long as when it comes to the final game the map is going to have a 1kx1k map, which when I tried generating took 30 mins.
I hooked VS into Unity using debugging and also using the Unity profiler, but can't see anywhere the info that I need to see how long each process is taking
turn on deep profile and sort by the cpu time . . .
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html
you can measure with this too
I've had deep profile on, how do you sort though?
just saying as well, 100 * 100 is 10,000. While 1k * 1k is 1 million. If you can notice lag when doing 10k, 1 million wont be feasible
Yeah, I think the issue is with my noise map generator, as it has a lto of calculatiobs it has to do, which means I am probably gonna have to chunk it up and hope that it works out. Though I am still curious as to what process is actually taking the longest
with this u can probably get a good idea
Share some profiler data with us.
Well bugger, those 15000ms executions don't look fun
now switch the Timeline to Raw Hierarchy . . .
That
Thought I can already see that CalculateNormals takes a lot of the CPU time.
Oh wow, that's surprisingly useful
That's my calculateNormals 
I like the part where you copy the entire triangle buffer, get a single int out of it, and then throw it into the garbage ... 3 times, per triangle
Getting triangles from the mesh buffer is pretty heavy. You might want to get and set them once instead of doing it separately for each triangle.
I’d blame Unity for bad API
I'd assume just getting them, setting into an array and then referencing the array each time would work fine?
Yes. Though remember that you need to set the whole array back to the mesh after all the changes.
Alright, here's to hoping that clears up some of it at least
You can use GetTriangles with pre made List to avoid allocation
I'm trying to make an inventory, but I'm having a little trouble. I thought about making a parent class and having a bunch of children inherit from that parent, that way I can create a list of "items" but I'm not sure if thats the best way to go about it. Any tips?
Guys, please help. I've been stuck on this for days. How can I achieve the touch drag movement from this following video considering that when you drop a block between two nodes it snaps to the closest one? https://youtube.com/shorts/pWCITdNGxEs?feature=share
make the blocks always check to see if they're at a "good" location, and if not, move them towards the closest good location
but how do I make the touch drag movement?
what do you mean by touch drag movement?
individual drag movement with touch input for each block like in the game
Oh i'm not a mobile developer so i'm not really sure how the inputs for touch screens work, sorry.
it's okay
If a gameobject with a script attached is destroyed using Destroy(this.gameObject);, and the attached script has some code in the Monobehaviour Update() method, is there any chance that the script might run the update method after the gameobject is destroyed? Or more generally does the script keep executing after the gameobject it's attached to is destroyed?
If it's already executing, it will keep on executing until it returns. Otherwise, update shouldn't be called on objects marked for destruction.
Can I return monobehaviour update i.e.
void Update() {
if (condition_to_be_destroyed) {
Destroy(this.gameObject);
return;
}
}
yes
I'm struggling with some seemingly simple math and was hoping someone could point me in the right direction
I've got values X and Y that always need to be 0.1 apart, relative to percent Z (from 0 to 1)
ie, if Z = 0, x = 0, Y = 0.1,
if Z = 1, X = 0.9, Y = 1.
Where I get confused is how to express this linearly, so Z can go from 0 to 1 without clamping on either end
calculation:
X = Z, if z > 0.9, x = 0.9
y = x + 0.1
Yes.
Cheers
This except it should be y = 1 - x
???
Nevermind ignore me
Im just confused haha
@fathom geode you mind me asking what the math is for?
Seems like an odd calculation
Extruding a spline based on percent, length needs to stay constant
i was imagining its some start/end point, like a scrollbar
oo cool
just to add onto the calculation: ideally you would do this
if z > (1 - difference)
x = 1 - difference
so you can adjust the difference to be anything without having to recompile the code everytime
how do i make a cube go between theese two points like a line renderer?
i already have the two points as vectors
idk if this is the right channel but does any knowif this package is broken https://github.com/Whinarn/UnityMeshSimplifier/wiki/Mesh-Simplifier-API#constructors
what you turn into rotation?
i already have the scale of the cube working using the distance between the points, but how do i angle it so its in between them
i dont understand
you keep piling up more and more things in your question
scale, angle
draw another picture with what you actually want
heres a really bad drawing
like you would use a line renderer
so the front of the rectangle is on one point and the back is on the second point
thanks so much, i made that way more complex then it had to be 🤣
🗿 sans = transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform.gameObject.transform;
try this
new GameObject gameObject => gameObject;
private void Start()
{
gameObject.transform.position = new Vector3();
}
just save before it
or better dont do it
Did you ever find a solution?
because if not I might see if I can animate the camera my self, but I'm not sure if that'll work.
I've got a weird one. I wanted to make some simple soft body stuff, so I followed a tutorial and it's perfect. But now I wanted a script to make it grow with time. For whatever reason, when growing, the soft body springs just totally let go and pretend like they dont exist. Video link for the soft bodies: https://www.youtube.com/watch?v=W3x143cYF88&start=197
Soft Body 2D Tutorial Jelly Effect - Unity (Easy)
Tutorial from Binary Lunar: https://youtu.be/H4MTeKT0QFY
Music used in this video
Boogie My Woogie no copyright Piano Boogie, royalty free 1940s Swing
royalty free Music by Giorgio Di Campo for FreeSound Musi...
Hello I'm currently working on a player selection system to allow players to view each other's names and stat values(HP/MP). I'm trying to use raycasting to detect player tag, but this only works properly for the client that is running the server.(which doesn't quite make sense to me..) For other clients, the detection field is way off the player model but is somewhat constant, it's as if there's an invisible box above the player model that can't be adjusted. I'm using Fishnet for networking.
Here's part of the relevant code.
{
if (Input.GetKeyDown(KeyCode.Tab))
{
DeselectPlayer();
}
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.transform.CompareTag("Player"))
{
NetworkBehaviour clickedPlayer = hit.transform.GetComponent<NetworkBehaviour>();
isHover = true;
if (clickedPlayer != null && clickedPlayer != this && Input.GetKey(KeyCode.Mouse0))
{
SelectPlayer(clickedPlayer);
}
}
else
isHover = false;
}
if (selectedPlayer != null)
{
UpdatePlayerInfo();
}
}
public void SelectPlayer(NetworkBehaviour player)
{
if (selectedPlayer == player)
return;
selectedPlayer = player;
UpdatePlayerInfo();
}```
Any idea or resource that could help me with making a Daily Quest system
i dont see anything thats really networking related that would make this work differently between server/client, you might have better luck in #archived-networking or pinned channels in there. Also this code doesnt really show too much of how you define where the names/values show
How would I use Astar pathfinding to kind of see if a cell is connected to another cell in a group of hexagon cells?
to clarify each 2d cell is a different object (with colliders and disabled rigidbody) and when a cell gets destroyed (killed) then i want to check all the cells and see if they are connected by another cell, if not the rigidbody should be enabled and it would float away
or is there some other algorithm/way to do it
That's not really a job for A* (or any pathfinding algorithm.) You already need to know connections before you can do pathfinding. You just need to check all adjacent coordinates, if none of them has a cell in them then it's not connected to anything
yeah but the issue there is that cells could be connected to more cells so like
if you break a support an entire section could disconnect right
ok well a group of cells is different from "a cell"
oh yeah i didnt really mention that did i oops
You could try a flood fill algorithm, if it doesn't fill everything then there's a disconnected section
good idea
Alright I will try. The issue doesn't seem to lie within the names/stats retrieval though. Since the object detection in the first place is working weird..
you dont keep connections in the node?
as references
no
the 'swarm' controller on the parent stores all of its cells
ive just implemented a flood fill algorithm to search for disconnected cells that I can just call whenever a cell is destroyed
Don't cross-post #💻┃unity-talk
So I've made a state machine to handle game logic. Currently I'm not using any inheritance, and I'm instead trying to handle state specific entry and exit behaviour by calling functions in other objects. The problem I've found however is that this doesn't offer enough control, and instead I'm basically having to write the same code I would have done if using inheritance but instead it's in scattered in different places which is definitely worse. Any advice? I'm currently planning on just switching to inheritance
I just copied Google -_-
How could i go about copying images from window's clipboard?
You would need to search for windows specific feature/library
I found that if I put the System.Windows.Forms.dll file in the project folder, Unity does the rest, but I cant find the .dll xD
is it bad for performance to have a coroutine permanently running this?
IEnumerator MyCoroutine() {
while (true)
if (myQueue.Count > 0) {
// things here
}
yield return null;
}
it checks if a queue has items in it each frame and idk if that is bad
Do you need it every frame, also, why bother with a coroutine?
no
Hello i have several question regarding collider2d i'm not sure if this is the right place to ask but here it is
1.) I Have 2 boxCollider2D 1 in MidevalKnights and 1 in Weapon ( as in the image )
2.) however i only have rigidbody on the MedievalKnights
Expected:
- when collider in the Weapon is hitting an enemy "Weapon is hitting an enemy" i damage them
Problem:
- When my player boxCollider hit an enemy it is also count as weapon hit which is not expected, how do i differentiate between these 2 colliders? Thanks in advance
yeah i need it running every frame in the background so it can immediately detect when the queue gets something added to it
coroutines that are suspended are cheaper than updates, coroutines that are executing each frame like yours, are just slightly cheaper than update
But FixedUpdate (50 checks per second) vs Update (which could be 140+ time per second), not many things need to be that instant.
Networking I can perhaps understand why Update (every frame).
you are trying to solve something that is typically solved with events/observer pattern
i am using delegate events on the WeaponHandler so the trigger is not actually in the MedievalKnights itself
i suppose i could make it in update now that i think about it but if its cheaper ill just keep it this way. i just wanted to know if it keeping it this way is bad for performance, apparently its not bad then, thanks!
so how do i properly handle these kinda thing?
Have you tried using layers? Then it's a simple check what's colliding with what.
what is processing collisions? enemy/player?
i guess player deals damage
then you need to relay events to the root for processing
ouwwh that make sense but i also wanted my player collider colide with the enemy
currently i dont set include layers to anything in both of the collider
the one that process -> trigger is from weapons the one who process the calculation is the player
this is what i do
maybe i should make the trigger and the calculation in the enemy instead? :/
i have been stuck here since yesterday XD
set of interfaces ICollisionEnterHandlerRelay etc
implemented on root
on the colliders are components CollisionRelay
they have field target, of type monobehaviour
when they receive a collision event from unity they cast the target to the interface, if cast is valid, the method is called
im really sorry i'm new to unity so i have might not understand what you are talking about XD
ok, what should i explain
or i can simplify the approach
simply have public void OnCollisionFromRelay(Collision col) on your root player controller
private void OnTriggerEnter2D(Collider2D other)
{
if (onHittingTarget != null) onHittingTarget(other);
}
Basically i wanted to know what collider is hitting with the "other" collider
so the code on your colliders/triggers becomes
private void OnTriggerEnter2D(Collider2D other)
{
_medievalKnight.OnTriggerEnter2DRelayed(this, other);
}
ohhhhh rightttt we HAVE THISSS
this
right let me try
XD
oke this works
i dont know if this gonna be costly or not tho
no
Layers.
You can specify layer masks for collision detection on colliders, so instead of hitting everything and then filtering off, you can just avoid generating unwanted events in the first place
You should have a "PlayerVulnerable" layer which contains hitboxes for stuff that hurts player (enemies, ebemy abilities, enviro), and the players "vulnerable" hitbox.
Then "EnemyVulnerable" layer which has the enemies body hitboxes, and the players attacks or whatever and any other stuff that can hurt enemies
Theoretically also a "neutral vulnerable" layer if needed, if you need effects that hurt both players and enemies (like bombs or whatever on your game)
This let's you have stuff like enemies that have "non vulnerable" portions of their hitbox.
Looking for code review / feedback
This is for a tetris inventory, like the one in tarkov
https://paste.ofcode.org/5C5W79U86uygVc6ytPPVG7
I am highly aware that my code is very bad, this is my first iteration to get it working, I am looking for feedback so that I can structure it better.
Hey, can you tell me how to import GLB file using GLB importer? I know how to do it from link but I need to load from project already downloaded glb file and create custom avatar from that
Heya
I have a body and head separated
But when i try to apply transform effects to it, nothing happens
Only general transforms applied to "kkkxd" work.
Is this a code question?
well quite
I'd like to know if there is a way to move it still being a child
maybe an option that i can mark i don't know
I tried looking for this everywhere in the manuals and google and etc
Nothing related to code. It has to be attached to the armature I think. So ask in #🔀┃art-asset-workflow how it can be fixed
sorry for continuing it here but
so you mean i can fix that through blender normally?
Probably. I'm not that familiar with modelling. You should ask in appropriate channel for that
Well, it's working fine on blender and animations. The real problem is that the transform does not apply to it. I think it's working just fine as a model
I'm trying to make an inventory, but I'm having a little trouble. I thought about making a parent class and having a bunch of children inherit from that parent, that way I can create a list of "items" but I'm not sure if thats the best way to go about it, because ill have like 100 or so files at the end of development that are just items. Any tips?
Your only other option is making items get constructed completely via the inspector using a very data oriented approach (or in code as functions). It would be one item class that has all the necessary information to construct any item type you want. A health potion would be a Usable and it would perform a Health modification when used, for example.
I think this approach is hard to design for and you are probably better off having a different script for each item if you want specific functionality. It is easier to understand and refactor as long as you don't make huge hierachy chains (like Item -> Weapon -> RangedWeapon -> Bow -> MyBow)
Keeping your hierachy depth low is the way to go as stated by @crude mortar.
Hiya, probably a weird question -
I want to take a gameobject(green thing) and move it based on the hitpoint of a raycast towards the red square ive drawn, how would i go about getting the direction and coords to transform it? 
Hello Sir, I'm trying to do a fuzzy sugeno method here, so I'm applying the method to the enemy, here is the link of the full code:
https://paste.ofcode.org/SfgSLQqLrMmBgqw3CD5A3b
The core code is in the function of EnemyAttack(). The output is NaN, what is seems to be the problem?
There likely won't be more than a layer of depth, but im curious about this inspector approach. While it does sound interesting, my main issue is that in my game every item will have a relatively unique function. ie: one item increases health, another increases damage, another causes your attacks to explode etc. etc.
yeah, so it may not be worth making it extremely modular if you know that most things will be very unique in function
Start debugging
find where the NaN starts
usually it'd be from divide by zero somewhere.
modularity is harder to setup and provides benefits later, but if you never get to that "later" (in terms of reusing stuff) then it's pointless
alright, so one parent class is the way to go? is there a way to have multiple children per file cause honestly im just dreading creating dozens of files with like 9 lines of code in them each lol
don't dread that
more code on the screen does not mean that the code is somehow better or more reusable
I usually try to go for exactly what you are dreading—many small files. If you don't need much code to make things work, you are probably doing something right
Hitpoint has a vector3. Just move to the vector
https://docs.unity3d.com/ScriptReference/RaycastHit-point.html
The problem is from inference system, the third step of my method.
and yes you can have multiple children per file if you wanted
I think as long as they aren't a Unity object
https://paste.ofcode.org/3b73KHdJZVLb7ZFUdAycZGm
This is the code, If I change the number, it will work, but it's not inline with my research
I believe Unity checks the filename for serialization purposes and so multiple per file would break it
this is 131 lines of code
Yes
maybe one or two parent classes, depends on your needs
but there won't be like, an issue with making a hundred files from a storage/speed perspective? i feel like that many files might lag the project?
alright i guess, thats fair
just my generic library of stuff I like to have in every project is hundreds of files, and that's before I even start the project
it is not that much slower than having a blank project
So the cause it's number/0, right?
Oh lord I just clicked the link to the script
What a terrible day to have eyes
Ok, thanks, but what if it's required you to divide it by zero? I mean, if the output is 0 and that output is to be divided by other output?
computer can't divide by 0, so you must not do it in your code
you can check for division by 0 and stop it before you tell the computer to do it
it is never required to divide by zero. It's a nonsensical operation
It's mathematically ambiguous what that even means. How many times can 0 go into, say, 2?
I tried to change this method to codes, I do exactly like the formula.
"How big will each slice of cake be if I divide it into 0 pieces?"
"How many pieces of cake will we get if we cut it into pieces of size 0"?
This is what divide by zero is asking, and it's meaningless^
Seen Animation vs. Math by Alan Becker? At some point it tries it and you visually see why it fails
Subtract 0, infinitely
well formulas are not programming, so oftentimes they just tell people "by the way, 0 in this function is undefined"
there are no rules to say "do not do it" in real life with formulas, it will just give undefined result
but when translating it to code you need to do some extra precautions to stop division by 0
since computer is not a human who can recognize that dividing by 0 is bad and avoid it for you
No, but I love things like that, i'll check it out, thanks!
So how do I take extra precautions to stop division by 0? Is there any example?
if (theDenominator != 0) {
// do the division
var x = theNumerator / theDenominator;
// blahblah
}
else {
// do something else
}```
The formula paper you showed here has an issue, what if x = b in the 3rd example? Does it take the second or third case of the formula here? It's also why you can didvide by zero, the conditions should be "less than", and not "less than or equal to"
a good example is calculating averages:
int numberOfObjects = someArray.Length;
if (numberOfObjects == 0) {
// we can't do the normal formula here since it would be dividing by zero
average = 0; // some reasonable default?
}
else {
float sum = 0;
foreach (float x in someArray) {
sum += x;
}
average = sum / numberOfObjects;
}```
So I should edit all the line in this https://paste.ofcode.org/3b73KHdJZVLb7ZFUdAycZGm, to decide not by "less than or equal to" but "less than" only?
Alright sir thanks
It should be something like
x < a
a <= x < b
x >= b
For the first example. So you have no ambiguity in case, say x = b, it goes in the last formula.
Ohh
So rather than this:
else if ((0.1 * maxNyawaPemain) <= nyawaPemain && nyawaPemain <= (0.4 * maxNyawaPemain))
{
// do something
}
I should do:
else if ((0.1 * maxNyawaPemain) <= nyawaPemain && nyawaPemain < (0.4 * maxNyawaPemain))
{
// do something
}
Yeah that's one of the two ways. Just make sure the <= is always on the right here
Okay, I will think about it
hello, do lot's of games use jwt in their games for authentication?
we have had this conversation earlier actually
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
are you reffering to me?
Nop
Can you divide the items into "categories" or "strategies" that are similar in behavior?
Like SmallHealthPotion and LargeHealthPotion probably are the same thing with just the Potency or whatever parameter different right?
yeah thats pretty common for OAuth
can I combine sqlite db with jwt?
different application layers, try and keep your DB layer seperate from your Authorization layer
you sound like what you want is an Asp.Net Web API, which has built in easy support for JWT authorization
maybe a little? but for the most part no. It's not a traditional invetory like minecraft or stardew, its a roguelike where every item affects a certain aspect of your playstyle, and as such has a different command to run whenever you attack or deal damage or dodge or whatever.
It sounds a lot like you can have a core PlayerStats or whatever as part of your GameState and each item modifies that, like "BootsOfQuickWalking" prolly adds a PlayerState.MovementSpeed modifier
probably something like that yeah, What i was planning on is having a parent class with functions like "onAttack" "onDodge" "onDamaged" etc, and every item overiding these functions or the players stats or something.
that sounds very difficult to maintain, I would invert that entirely
don't know what it is, I just want to create normal unity online game
how so?
Your inventory items shouldnt be aware of the world outside of em, they just prolly have some kind of MutatePlayerstats function or whatever
Logic for what your Playerstats actually mean should exist in some kind of other place
Your inventory items should be "Is a" classes, not "does a" classes
Try and always seperate your classes into 2 bins:
- "Is" something (I call these Models)
- "Does" something (I call these Services)
Try not to overlap the two, Services can manage, CRUD, Read from, and Mutate models.
Models just sit and look pretty and hold your information, but they dont "do" things
I typically follow the paradigm that my MonoBehaviors are largely all my Models, and my Services are POCOs... mostly
While that's fair, i think you might misunderstand. almost every item will be unique and not every item just affects stats. For example, an item might spawn a gernade that drops on the floor every time the player makes a critical hit, or an item might regenerate the players health every time he dodges.
for every item i'll need a unique function that does something every time the player does something
yeah so, visually that can happen, but I would strongly encourage you to design your code so your GrenadeMakerModel doesnt actually make the grenade.
It can perhaps have the SpawnsProjectile strategy, and it can have SpawnedProjectile = GrenadeModel, and perhaps ProjectileCount = 1
But the logic of spawning the Grenade should prolly be on your ProjectileService which manages CRUD for all your Projectiles... etc etc
i have a ui rectTransform that i manually have to add to the clamped background size so that the camera moves to the edge and the player can walk to the edge of the background without blocking part of the background...when an aspect ratio is changed on a diferent monitor the background starts showing. how can i always add the size of the ui to the background so it is correct on any screen size? first image shows 1920x180, the second image is the other size 1280x720 and the ui is slightly a different size
float minX = mapMinX + camWidth;
float maxX = mapMaxX - camWidth + 5.07f;
float minY = mapMinY + camHeight;
float maxY = mapMaxY - camHeight;
float newX = Mathf.Clamp(targetPosition.x, minX, maxX);
float newY = Mathf.Clamp(targetPosition.y, minY, maxY);
the code clamps the camera to the background but then adds the x value of the ui manually. how can i make this work with every aspect ratio. the +5.07f is to make sure the ui is at the edge. but this number doesnt work for other sizes
is your UI on a canvas? You should be able to just get the Rect of the Canvas itself
yes it is, i tried getting the rect of the ui element itself but its 500 width which is way too much
you can set the canvas to camera mode where you bind it to your scene's camera, and it will auto hug to the camera's viewport or whatever
I don't really know what you mean by ProjectileService, but I assume its a projectile manager for the whole game? don't really know why you would do that. I can see your point with the spawns projectile bit, that would work fine if I had a projectile manager, but that's just one of the many effects that can actually happen. If every item is going to be doing something unique, why not have unique functions for all of them? I can see how you would do something like this, but I don't really see why.
Render Mode
do you actually need unique functions for every single one.
I would put money down that chances are you absolutely can "group" them smartly into common behaviors and reduce your problem space tremendously
that seems to work better but objects in my game are now ontop of the ui. how can i make the ui always be ontop?
by default your canvas should be on top, double check your layers and sprite rendering orders on the stuff in your UI, and same for all the other stuff in your scene that is showing up in front of the UI
I will warn that this approach has an upfront cost and can have high maintenance if your problem space changes at all throughout development.
Alright, i'll think about this and come back to you, but before that, is there an actual point to doing it your way? What's the benefit?
IIRC all UI elements you create default to being in the... I think its literally called the UI layer, which is by default the front-most rendering layer
reduce your problem space tremendously
👆
they are all default layer and my ui is on a layer higher in the layers. do objects with sprites need to be under the ui in layers?
yeah they default are on the default layer IIRC
@mighty yew if you have like, lets say 200 unique items, but you can actually just categorize them into say, 10 unique "strategies" or "behaviors" if you will, now you have 10 functions to write instead of 200.
Im sure you can see the appeal of that ;P
does this look right? they are still ontop of the ui
Lower = In front
the bottom in that list is the front-most, and the top layer is the backmost
ahh okay ui is just hardcoded in unity so ill make my own ui option
you can change the sorting layer on the canvas
you can just drag it down
or wait can you modify it
I thought you can, maybe you cant
You can't, they are editing the layer definitions
TIL
it is just a 32 bit mask for all layers, the ordering happens separately
@smoky basalt do yourself a favor and put UI layer at the very bottom XD
wait what? I thought the order mattered
in that editor
i set the ui to pause like the pause menu but everything is still ontop
Im thinking of rendering order layers arent I
yeah thats the other layers isnt it lol
i even moved the canvas to the bottom of hierarchy
@smoky basalt sorry mate those layers are the physics one, for sprite rendering order stuff theres a totally seperate group of layers you gotta edit
hey Team, new to the server. Looking to post about inviting any interested Dev to join our** BlackThornProd team project: 7 Devs Build a Game WITH COMMUNICATION**.
Is there an appropriate channel where I can post it with all the details?
its in that same editor though IIRC, at the top theres uh... "Sorting Layers" Or whatever they are called
ohh for sprites
!collab 👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
if ui isnt a sprite its an image how do i add it to sorting layer
thank you lmaooo
they really outta rename "Layers" to be like "Physics Layers" or whatever
I dunno if they get used for stuff other than that
well now the ui isnt going to the edge of the screen..
var c1 = spectrum[3] + spectrum[5] + spectrum[4];
if (c1 < 0.0002f)
{
// player.GetComponent<playerMovement>().noise = false;
}
if (c1 > 0.0002f)
{
player.GetComponent<playerMovement>().canMove = true;
Debug.Log(c1);
}``` in this snippit, canMove is not being set to true, but the debug is showing
this is when its 1920x1080 other ratios dont work
im clamping the ui to add onto the background so the camera can go past, but adding the rectTransform didnt work because the image isnt a sprite
I'm honestly a little confused as to what your method is. What I understand is that theres a statsFile:
health = 3
damage = 4
void changeHealth(int x) {health +=x}
void changeDamage(int x) {health +=x}
and then every item file, for example a potion:
//InheritFromItem
overide void MutateStats(){
statsFile.changeHealth(1);
}
Is this what you mean?
are you sure it isn't being set to true? how can we tell from this snippet that something else isn't setting it back to false
this was my original problem but it was almost solved with screen space- camera
sort of I suppose, theres many ways to implement it.
I would go with implementing interfaces on your items personally
Interfaces? the "changehealth" functions?
C# interfaces, which by implementing them also inherently implies what behaviors they adhere to (this lets you have items that can have more than 1 behavior too)
Alright, it's going to take me a minute to read up on those since I haven't heard of them before.
so something like
public interface IHealthBehavior {
int HealthModifier { get; }
}
public class HealthPotion : MonoBehavior, IHealthBehavior {
[SerializeField]
private int healthModifer;
public int HealthModifier => healthModifier;
}
Something like that
but then if you want to add the IThrowableBehavior to the HealthPotion, to enable it as a "throwable item" as an example:
public interface IHealthBehavior {
int HealthModifier { get; }
}
public interface IThrowableBehavior{
int MaxThrowDistance { get; }
}
public class HealthPotion : MonoBehavior, IHealthBehavior, IThrowableBehavior
{
[SerializeField]
private int healthModifer;
public int HealthModifier => healthModifier;
[SerializeField]
private int maxThrowDistance ;
public int MaxThrowDistance => maxThrowDistance ;
}
boom, now it "identifies" as both modifies health and is throwable
and you just sort of aim to break up your various "behaviors" into interfaces, and can apply any amount of em to any given item
Where is the actual "throwing" or "healing" code stored?
I would go with Strategy Pattern or maybe even Mediator Pattern, to create a Service that does the actual game state manipulation with the items
Honestly a lot of this though could be boiled down to just a Flagged enum which I think Unity can serialize? IIRC it serializes to like, a list of checkboxes?
you could then add a bunch of nullable properties for every behavior, and then your editor hides/shows the properties if you have a flag checked off or not
itll be a bit more cumbersome potentially but might be easier to work with in the consumer
I'm not really sure what either of those are sorry.
What would be the benefit of this over a general inheritance approach and virtualization. I probably don't take advantage of interfaces that much beyond using them for type identity when using generics and stuff.
you cant inherit from multiple classes
you can, however, implement multiple interfaces
Right, but say, Item -> HealthPotion
Actually, ok yeah I can see the usage of interfaces this way
Rather, it would probably make more sense to do some inheritence here, and tack on the throwable interface on the inherited class
Flagged Enum is also totally valid, but you'll wanna do some fancy work with the enabling show/hide of your various fields based on enum values selected
Has anyone ever had issues serializing an object with a Dictionary as a property using Newtonsoft Json Utility? I have an object with a Dictionary property that I know has items in it, but when I save it in a json file it is empty. I have no clue why 😭
yeah if you want all health potions to be throwable, you implement throwable behavior on say, HealthPotionBase
If you want them not throwable by default and then you make a special ThrowableHealthPotion, you put the interface on that child class
Man, I really want to dive into ECS but too committed to my projects
I gotta jet in a sec, I got a technical interview for a new job but feel free to ping me with questions still, but prolly wont be back for an hour
It's alright, i'll try to make some sort of sense of this
god I hope its not just a bunch of "re-write quicksort from scratch, now write code to invert a binary tree" type of stuff, nngh
Do you know anything about the json dictionary thing before u go
im not really sure on the enum thing, and i'm almost certain that it would make this several times harder, but the interfaces are actually pretty helpful
Its a common issue IIRC, I believe that one should get results from googling
I have been trying but I haven't found the reason
im imagining I can have an item interface that every item inherits from, and then a "healthchange" or a "on-hit" interface that only certain items inherit from
interfaces mostly will involve you wanting to do some if (item is IThrowable throwable) .... casting "is a" checks
enums will maintain type safety and wont need casting, but your objects will all have a whole buncha null properties on em
and then I can just have a list of items? im hoping I understand this
you dont inherit from interfaces, they are more like a contractual obligation your class says it will adhere to.
You "implement" an interface, and "inherit" from a class
basically when you go
MyClass : IMyInterface
You are committing to MyClass implementing whatever IMyInterface said it has to implement
like a contract MyClass has signed and promised to adhere to, and if it doesnt, it throws a compile time exception and wont compile, and says "Yo, you said you'd do this thing but you didnt"
Ok, that makes sense
An example of an interface I use is one I call IEntity, such that any script that implements it will be guaranteed to have a Stats object, an Ability class object, and an Equipment class object. This is helpful in unity because instead of checking for specific components of a gameobject, I can simply check if it includes this interface, making operations easier when doing sphere casts and such. Additionally, instead of exposing a script completely, this reference will only allow you to access what the interface implements.
@leaden ice @crude mortar @simple egret Sir, I found it, there's no more NaN, turned out the problem is in the last stage, it's 0:0. So I use this way to decide the output. I put "0" as defuzzy in else {}.
You'd need to use some casting method, probably want to avoid raycasting directly. Some combination of spherecast/boxcasting with distance calculations is what you'll probably want to look into.
im using ezy slice, so i want to put planes along the sides and cut the things intersecting with the camera border
basically clearing the mesh in front of the cam
guys im having a problem here, i made a Player movement system, it works perfectly, but when i restart unity, the vision only moves in the X axis.. Here's the script btw: https://hatebin.com/rprqcbrcih
and if i dupllicate the player and delete the original one, it goes back to normal.
https://www.youtube.com/watch?v=XrqesjfcitU
Zero actually has the idea about locating what's in vision of the camera, but even with that information, you'll have to figure out the bounds relative to the camera of the object you want to trim.
Let's explore how you can detect when an object is inside the players camera view by using the camera's frustum and axis-aligned bounding boxes (AABB). This takes advantage of Unity's built in GeometryUtility class that provides some helper functions to make this easier.
The fi...
im trying to create something like this, so i dont know if thats what i need https://www.youtube.com/watch?v=8rr83zwzlOA&t=1s
This is a nice visual illusion game mechanic. The original game is called Viewfinder. Make sure to check it out.
🔊 200 Likes! 🔊
⚠️ Alright, as people are really eager to know how the code works, I'll do a long stream soon and will code this whole thing from scratch because I can't share the code due to a paid package I'm using the cut the meshe...
is there a simple way I can get an x, y output from a bool[,] depending on whether or not a certain element is true or false? I wanna get the indices in the array that are true
preferably without a for loop
you will need a loop
but a better option may be to just use a HashSet<Vector2Int> in the first place, rather than a bool[,]
on the left, you can see a bool[4,4] and on the right a bool[3,3].
I want to check if the current location of the 3x3 is valid in the 4x4
(providing the full context for my question)
using a hashset would leave me without the data I need to verify if a field is taken
assuming I can make a class that holds a Vector2Int and bool and make a HashSet out of that is a better option, would that be the middle ground im looking for?
no it would not
HashSet<Vector2Int> whiteSpaces = new() // or blackSpaces?? IDK which is which
bool IsTaken(Vector2Int space) {
return whiteSpaces.Contains(space);
}```
the HashSet<Vector2Int> gets you everything you have now PLUS an extremely easy list of "taken" spaces (just iterate over the set)
ah I see, it would make more sense to me to invert the whole thing since I only need to know the open spaces tho. but th e logic is sound
keeping all positions in a hashset, and removing them when the spot gets filled @leaden ice
yeah that works
are HashSets serializable to the editor?
not directly
you will have to serialize it as a list
and read it into the HashSet in Awake
in that case I might keep the 2D array for the initializing data and convert to a hashset to manipulate
yeah
or that
but 2D arrays aren't serializable either
only 1D arrays
you could use an array of Vector2Ints, or a list of them
I should note that I am using Odin Inspector, so a lot of the serialization limitations are not applicable here
I was also just thinking that
Do you use assertions (Assert.IsTrue()) in code or rather exceptions for cases which should not happen like "Trying to add vehicle to inventory" (what should be already disallowed somewhere else)?
Assertion seem to be convenient to spot invalid states or bugs in the code but after they are removed in build the game might end up in some weird state if that condition is met somehow...
https://odininspector.com/documentation/sirenix.serialization.hashsetformatter-1 if it isnt, it seems easy enough to implement
If that exists then it seems like it should work out of the box
altho im quite certain it will be serialized to JSON by default
same as with dictionaries
Odin is a thing that I own that I always forget about 😆
haha
we use the serializer and validator for our projects
validator is quite a powerful tool we have in the pipeline
serializer is nice, but most of the inspector stuff it provides can be done manually without relying on it.
It does really speed up my tool production tho
does anyone know how to calculate the size of a ui element in the canvas. it says the width is 846.2356 but i need the actual sprite size which is 5.07f how is this conversion done?
what do you mean by "actual sprite size"?
i know rectTransform is different from transform
i just dont know how to get the transform size of a rectTransform
what does "transform size" mean in your mind?
this is 14.13 if its a rectTransform its based on width
that's a position
but
It's more complicated than you're thinking.
The coordinates of the RectTransform are in Canvas space, not world space. And the conversion between canvas space and world space depends on the canvas render mode
as well as the canvas scaler
so - maybe you could explain exactly what you're trying to accomplish here?
I was about to ask for clarification as well, its a bit unclear
if you would please look in #📲┃ui-ux you would see my issue. im trying to clamp the camera to the background but the canvas overlays. i want to add the canvas to the x so that the clamp also shows the background+ the canvas
Write unit tests!
hey guys sorry for double question but I posted this in #💻┃code-beginner before a huge code block and it kinda got skipped, but I just need to know how would I go about getting the horizontal FOV of my camera in degrees? camera.FieldOfView returns the vertical fov in degrees, which as can be seen here works fine for moving the center of my vignette, however I need to find a separate value for the horizontal FOV for the scope thingy I'm doing so it scales correctly horizontally
probably this?
float horizontalFov = cam.aspect * cam.fieldOfView;
There's also a function in Camera
But they should work the same
Correction: The formula is far more complicated (https://en.m.wikipedia.org/wiki/Field_of_view_in_video_games#Field_of_view_calculations), and you should use the Unity function.
In first person video games, the field of view or field of vision (abbreviated FOV) is the extent of the observable game world that is seen on the display at any given moment. It is typically measured as an angle, although whether this angle is the horizontal, vertical, or diagonal component of the field of view varies from game to game.
The FOV...
thanks man I'll try it!
Oh I would 100% absolutely use this @steep scarab
the formula might not be as simple as I said
it was just my first instinct
ah ok thanks man appreciate it!
this ended up being close enough if not just a tiny bit off. the function seemed to be having compile errors but I'm sure I can figure it out later
that's a static method not an instance method
I need to take my ass back to #💻┃code-beginner
call it directly on the class, not on an object reference. it's just Camera.HorizontalToVerticalFieldOfView(<parameters>)
oh my goodness I'm so dumb 💀
thanks lol
also your local variable is misleadingly named, it should be verticalFov not horizontalFov since that method returns a vertical fov
ah wait, you're just using the wrong method actually. you want the VerticalToHorizontal one since mainCam.fieldOfView is the vertical fov
yeah lmao 😭
appreciate it tho man thanks I feel dumb asl now tho lol
any help plz?
#💻┃code-beginner message
Hey @somber nacelle, do you know why an objects properties that have values would be empty upon the object being serialized into a json file? This problem is actually driving me insane
No matter what I do there are no values in the json file even though there are values there before it is converted
don't ping people into your questions
ok
Why: because a lot of reasons. Show your actual code so people can help
It's kind of ugly rn because I have been trying a bunch of things to fix it. But the problem hasn't changed at all
The methods in this file are also called by my game manager script, but I have printed out the values to confirm that they are there, and it really isn't empty
first guess, i dont think newtonsoft serializes auto properties
this won't fix your issue, but lines 39 through 47 can be reduced to just
string[] enemyIDs = enemyStates.Keys.ToArray();
bool[] enemyStatuses = enemyStates.Values.ToArray();
How come you are using json utility when you have Newtonsoft? Havent used json utility specifically but I dont think it can store that
hes not
I was using newtonsoft, I tried json utility to see if it would work and it didnt either
they are serializing with JsonUtility though
He is
Ah.
That is good, if only I could get the other thing to work lol
try with fields instead of properties
I have tried that. Aren't properties supposed to be serializable?
not with JsonUtility 😉
I was using newtonsoft before and it didnt work
nah, make backing fields with serializefield i reckon
I am just going to put it back to newtonsoft as well bc jsonutility isnt helping
I would make backing fields as a work around if having fields worked
Changed to fields and newtonsoft, this is the output in the file: {"EnemyIDs":[],"EnemyStatuses":[]}
Originally I wasn't converting my data into arrays and just leaving it in a dictionary, which is supposed to be supported by newtonsoft. I only chaanged it to this because it wasn't working
I am just completely lost here
Ok I think I figured it out. The method is being called twice which somehow results in the output being empty. Idk how that is happening though
Hello im using rigidbody moveposition to move my enemy toward the player but for some reason they start slowing down as they reach the player. is there a way to keep the speed. i think they are faster the further away they are from the player as well which i dont like
Vector3 dir = (player.position - rb.transform.position).normalized;
//Check if we need to follow object then do so
if (Vector3.Distance(player.position, rb.transform.position) > minDistance) {
rb.MovePosition(rb.transform.position + dir * speed * Time.fixedDeltaTime);
}
Does anyone know why the buttons from this script are double triggering? I have no idea why this happens. ```using UnityEngine;
using UnityEditor;
using System;
public class TestingMenu : EditorWindow
{
public static Action saveEnemyState, loadEnemyState, addEnemy;
public static string EnemyID { get; private set; }
public static bool EnemyState { get; private set; }
[MenuItem("Window/Testing Menu")]
public static void showWindow()
{
GetWindow<TestingMenu>("Testing Menu");
}
void OnGUI()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Save Enemy States")) saveEnemyState();
if (GUILayout.Button("Load Enemy States")) loadEnemyState();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Add Enemy")) addEnemy();
EnemyID = EditorGUILayout.TextField("Enemy ID:", EnemyID);
EnemyState = EditorGUILayout.Toggle("Enemy Is Alive:", EnemyState);
GUILayout.EndHorizontal();
}
} ```
This is the cause of my problem from earlier
unless you are changing the value of speed or you've removed some code between the first line and the if statement then your movement speed isn't any slower. however if you only move it when the distance is greater than your "minDistance" but the player keeps moving even when this object reaches that minDistance it may appear to start and stop over and over
it is in fixed update should i move to update so it calculates better?
no
awesome ill just try using addforce and see if that works better
Does anyone know if GUI layout buttons in Unity editor windows normally double trigger when clicked? Or am I doing something wrong here?
Lol, my brain is dead. Instantiating a plain class with [Serializable] should work like that or not? I cannot comprehend how is that possible: values chunkWidth and chunkHeight are serialized properly with 50. In debugger they are set to 50. But my array inside this object is instantiated using other values (12,10,12). But I create this array in the constructor. And the values which are used for this are serialized properly. I cannot comprehend this. When I call this ResetCubes() from outside script in Start() method then it works. 
unity cannot serialize multidimensional arrays
To serialize multimensional arrays, you can make a struct with an array as a field
make the struct system.serializable
then make an array of the struct
That will allow you to have a multidimensional array in the editor window
no, i don't want to serialize it, I'm creating a new one in the constructor
I can remove [SerializeField] for private Block[,,] cubeMap; because that doesn't work at all, you are right it is not serialized
You should upload the code, it would be easier to understand then screenshots
Right
but you are not calling the constructor. your model field is serialized which means unity will assign the serialized instance. which of course means no multidimensional array because that cannot be serialized 😉
so serialized classes don't have their constructor called?
why don't you do some debugging and find out
also boxfriend have you ever had an issue with GUILayout buttons triggering twice?
i don't use it so i don't have info about it. if i knew the answer to your question i would have already provided it
Ok, thanks
That's so weird that it does that. So now I have to go set up some stupid boolean thing to make it not trigger the second time? It doesn't make sense lol
looks like the constructor is called
Yeah, I don't see why it being serialized would prevent the constructor from being called when using the new keyword
did you remove the field initializer that creates an instance of the Chunk class to ensure that unity's deserialization is actually calling the constructor?
the constructor runs before the serialized values are copied over
so your width/height etc will not be set when the constructior runs
you can't really rely on the constructor in the context of serialization in Unity
ok, I suppose that's the problem
I suppose the instance is first created and then public vars are set by the serializer
I have assumed that the public vars will be already set to inspector values when the object is instantiated
this is why using the debugger is important. so you can see what exactly is happening and when
so I suppose it's not worth doing anything meaningful in the constructor if using plain classes because that's bug prone
don't do anything that relies on any of the serialized values in the constructor
ok, thanks for help
Quick question. A while ago I had been using visual studios and it had given me some useful help in coding. For example I would be typing "public Vect" and it would predict and give different options that I can finish it with such as "Vector3" and all these would be a light green/blue color. However, now my new version does not do that at all nor does it have the lettering green/blue making it blend in with a lot of other code. Is there an option somewhere to turn that on again?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Thanks!
im in one helluva delema. I want to make a progressive shotgun reload (reload shell by shell over time until full, but can be fired at anytime during reloading as long as there is one shell in the gun) I use a coroutine to time the reloads then call a function to manage the change in ammo and call the corutine again to prepare the next reload. I am indecisive on how to cancel out of reloading, do I just clear the coroutine and prevent reloading with a change in boolean?
You could. Like have the "continueReloading" bool which is checked before reloading another round, and if the player tries to fire it is set to false and they fire when the current reload completes
it really wouldnt matter much which one u choose, regardless the reloading is either gonna swap the value of the bool or start another coroutine to continue reloading. Id probably go with stopping the coroutine
ok thanks
both of you
Hi, im making a script to read text from a txt inside the resources folder. I just read that using resources folders is not recommended so Im asking if this is true
It certainly has drawbacks.
Basically everything in Resources will be loaded into memory immediately when the game starts
So it's bad for memory usage if you only need the data sometimes
well i need the text to put it inside a list at the start so its just once
It stays in memory
Any reason you can't just drag and drop it into your list?
As a TextAsset
I want to have a txt to add more words in time
and if i change something in the script the list just clear itself so i dont want to write that much
i mean if i change the name of the list and that kind of things
I gotta reask this because I don't think anyone ever had any ideas on it, but I used this tutorial to make soft body objects; it worked perfectly:
https://www.youtube.com/watch?v=W3x143cYF88&start=197
But then I made a simple script to scale the localscale with time, and while growing, the objects' spring joint completely just let go and the thing collapses, while growing. It become's a rigid soft body again once it's done growing.
Soft Body 2D Tutorial Jelly Effect - Unity (Easy)
Tutorial from Binary Lunar: https://youtu.be/H4MTeKT0QFY
Music used in this video
Boogie My Woogie no copyright Piano Boogie, royalty free 1940s Swing
royalty free Music by Giorgio Di Campo for FreeSound Musi...
Is there a difference between these?
private void Update()
{
currentZoomState = inputManager.Zoom;
}```
```private void Update()
{
bool currentZoomState = inputManager.Zoom;
}```
Yes, in the update function, there is a brand new variable being created each frame
in the first one, there is a single variable that is created, and then updated each frame
yes, the first is a field whose scope is the entire class. the second is a local variable that can only be accessed within the Update method
in the second one, the variable is deleted at the end of each frame and recreated
i recommend looking up variable scope to understand how it works
^^^
The second variable can only be used inside Update too
You can setup a script to run during edit time and auto populate your list, so its all preloaded at compile time
alright guys thank you all
after messing arond with calls that prevented it from working correctly, shotgun reloads as intended
Can even do a custom importer for a type of file extension you specify for your text file, and then it imports it instead as your actual output object type you need it to end up as
no way to dump a txt file into a list without reading it on resources then?
As I just said above, you can instead make it an asset and change file extension
And use custom importer to convert it to your actual object you need it to be
Thus you "preload" all that work and compile it in, so you aren't doing all that work on boot up
I have this code right here:
if (Physics.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition)/* start position */, Vector3.down /* direction */, out RaycastHit hitInfo /* hit location info */, maxDistance, layerMask))
{
transform.LookAt(hitInfo.point);
}```
I have a sprite in a 3D world view and I want it to rotate to where my cursor is. I have tried countless methods found on forums, video tutorials and a suggestion by a partner of mine. nothing works. I cam up with this solution, but I found out about a bug(?).
`Camera.main.ScreenToWorldPoint(Input.mousePosition)` this returns a static value relative to the player's position and not where the mouse is. I tried applying it to different GameObjects, even an independent one, but this seems to be a reocurring issue. I am requesting for a solution to my problems.
verison is 2022.3.5f1 LTS
@topaz sapphire no reaction images or off-topic
I can't seem to understand the point made
Input.mousePosition is (x, y, 0) which will always return the camera position
If you want to cast a ray out of the screen where the mouse is, use
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))```
sorry to bother again but the folder StreamingAssets have any disadvantage like Resources?
I made the code, but it seems to rotate the X and Y axis, but I want to rotate only the Y axis. how would I do that?
found the solution, thanks!
I have an issue, when i push S to turn the bool "isPogoing" on the input becomes true, and it triggers fine, but if i hold down S the bool stays true for a while an doesn't switch off even if i let go of the key, i've fixed the problem by removing verticalinput which gets the y axis, but i need it for controller support so im confused how to fix it, heres my code if (Input.GetKey(KeyCode.S)||verticalInput<0) { isPogoing = true; isAttacking = false; } else { isPogoing = false; isAttacking = true; }
trying to make a shotgun spread, any advice on how to make this work? is there a project on to plane that this will work with or? or am I just dumb?
!code 👇 because attempting to read that font is a pain in the ass
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Make it 2 separate if blocks. One if it's not a controller and S is pressed and another is of it's a controller and vertical input is less than 0.
public Vector2 spreadArea = new Vector2(1,1);
bool readied = false;
public override void weaponFunctionShoot(Transform origin, GameObject bullethole)
{
reloading = false;
base.weaponFunctionShoot(origin,bullethole);
for (int i = 0; i < pellets; i++)
{
var spreadAreaTrue = new Vector3(Random.RandomRange(-spreadArea.x, spreadArea.x), Random.RandomRange(-spreadArea.y, spreadArea.y), (Random.RandomRange(-spreadArea.x, spreadArea.x)));
var dir = spreadAreaTrue + origin.transform.forward;
if (Physics.Raycast(origin.transform.position, dir, out RaycastHit hit, 99))
{
Enemy hitTarget = hit.transform.GetComponent<Enemy>();
if (hitTarget != null)
{
hitTarget.takeDamage((weaponData.damage) / pellets, transform.parent.parent.parent);
}
else
{
Instantiate(bullethole, hit.point, Quaternion.Euler(0,0,0));
}
}
}
}```
!cs
Is this your own Random function 🤔
Oh it's just using the obsolete one for no good reason
public int pellets = 1;
public Vector2 spreadArea = new Vector2(1,1);
bool readied = false;
public override void weaponFunctionShoot(Transform origin, GameObject bullethole)
{
reloading = false;
base.weaponFunctionShoot(origin,bullethole);
for (int i = 0; i < pellets; i++)
{
var spreadAreaTrue = new Vector3(Random.RandomRange(-spreadArea.x, spreadArea.x), Random.RandomRange(-spreadArea.y, spreadArea.y), (Random.RandomRange(-spreadArea.x, spreadArea.x)));
var dir = spreadAreaTrue + origin.transform.forward;
if (Physics.Raycast(origin.transform.position, dir, out RaycastHit hit, 99))
{
Enemy hitTarget = hit.transform.GetComponent<Enemy>();
if (hitTarget != null)
{
hitTarget.takeDamage((weaponData.damage) / pellets, transform.parent.parent.parent);
}
else
{
Instantiate(bullethole, hit.point, Quaternion.Euler(0,0,0));
}
}
}
}```
it the one in the manual, is there a better one?
are you using an ancient version of unity?
2021.2
Then it's not "the one in the manual"
it probably also tells you what to use if you hover over it, it's gotta be underlined for a reason
done
so how can I
its still delaying when the bool is false
like if i hold down the bool for too long it stays true for a long time
Share the updated code.
{
isPogoing = true;
isAttacking = false;
}
else
{
isPogoing = false;
isAttacking = true;
}
if (verticalInput < 0)
{
isPogoing = true;
isAttacking = false;
}
else
{
isPogoing = false;
isAttacking = true;
}```
That's not what I suggested.
You still need to check wether the controller is used or not.
vertical input calls the y axis which basically uses the controller input tho?
is there another way?
But you don't want that if statement to be evaluated when the controller is not used, do you?
no i mean like I dont want the bool to be true when the button isnt being pressed like immediately, my problem is everytime i press the button for a little too long it stays true even if i let go, i want it to immedately become false when the player lets go, if i only have the button be S its fine, but for some reason verticalInput is making it true for longer even if i let go of the buttton, i want the isPogoing bool to be false as soon as the player lets go of the button
Well, that just means that your vertical input is being < 0 for a longer time.
have you considered that your numbers being passed to Random.Range may be too large?
yea i dont know why tho
Well, where do you set it? Debug it properly.
verticalInput = Input.GetAxis("Vertical"); i put it in the update function and the code above is in update as well
but thats how im calling the verticalinput
the values are literally 1 and negative 1
that cant be too large can it
is that what they show they are in the inspector?
Try GetAxisRaw instead.
in that case i don't see why you need the three Random.Range calls when you could just use Random.insideUnitCircle and set z to 0 (unless you want it to potentially shoot backwards, in which case keep your z as it is i guess)
yeah the values just needed to be tightend im actually just a moron
oh my gosh okay ty getaxis smooths it from 0 to 1 while getaxisraw returns it exactly
Yes
might be worth it to just use getkeyup
hm how come
its snapping it on and off i had getkeydown and getkeyup before but it just seemed like too much writing
Just seems like a good trouble shooting step. you're already writing all the code out twice, it shouldn't be much less efficient to ask the program to check for GetKeyUp instead of a blanket Else, which has been finnicky for me in the past
ah okay thats a good point
So I am having a strange problem where my .editorconfig file is simultaneously being detected by Visual Studio and Rider, and yet not actually being applied to my code editor, and its very annoying because its causing my personal code style to just... be ignored on unity projects, so lots of stuff gets highlighted as a problem that I dont want highlighted.
Anyone had this before?
Its error'ing it as missing braces, but preferences clearly have loaded that to be not an error
ok so i want to make interactables in my game
basically click: call a function in a script
thing is: i need the script name to be able to call functions in it, but the script names will be different bc the scripts are different and need different names for better identifying.
my solution to this was to get all scripts in the object(the object will only have the interact script in that case) and get the 1st script and call the function in it, but i have no idea how to do that. tell me if this is an xy problem and if there is a better sollution
this is my current code:
public class InteractTest : MonoBehaviour
{
public bool open;
public void SetState(bool newState)
{
open = newState;
}
}
public class PlayerInteract : MonoBehaviour
{
private PlayerInventory PI;
public const float intRange = 4f;
void Start()
{
PI = GetComponent<PlayerInventory>();
}
void Update()
{
if(Input.GetMouseButtonDown(0))AttemptInteract();
}
void AttemptInteract()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit;
if(Physics.Raycast(ray, out rayHit, intRange, LayerMask.GetMask("Interactable")))
{
GameObject other = rayHit.collider.gameObject;
GameObject curItem = PI.HeldItem;
}
}
}
You can just use the EventTrigger component
and hook up the PointerClick event to your various script functions
(just make sure your camera has a PhysicsRaycaster on it, and your scene has an EventSystem in it)
alr, ill try looking further into that
by eventsystem you mean something like this right?(i have absolutely no idea how this got into my scene but its here)
yes that
it gets added automatically whenever you add any UI element to the scene
you can also add one manually by GameObject -> UI -> EventSystem
oh makes sense, i was trying to do some pixelization with a renderimage
don't worry it's for non-ui stuff too with the approach I described above
is the standalone input module also nescessary?
yes
alr
wait is the standalone input module the new input system
no
it's the input module for the old input system
there's a different input module for the new input system
oh alr
bc when i searched for the standalone input module i only found videos on the new input system
thing is: i need the script name to be able to call functions in it, but the script names will be different bc the scripts are different and need different names for better identifying.
A lot of what you just wrote there doesnt really mean anything in the context of C#. Id recommend getting more familiar with the lexicon of C# so you can better convey what you mean here.
"script name" isnt a thing in C#, Im not sure what you mean by "script name"
file name
or at least typically "script name" would just be the file name
you shouldnt care about file names like that, you deal with "classes" in C#, which are declared in your files
ok so to declare a variable to store a "script"(FileName VarName = new FileName;) i can just use the name of the class?
as filename
wait lemme reformulate the question
largely speaking... you shouldnt really be even discussing handling file names at all in this context
is FileName VarName = new FileName; correct or is ClassName VarName = new ClassName; correct
the second one 🙂
alr, thank you
pretty much always you keep your FileName.cs to be the same as the class you declare inside of it
and, furthermore, theres stuff other than classes in C# you can declare, like enums and interfaces
but in that case id have to keep my different interact scripts in different folders right? bc the class name would just be "Interact"
Its typically a good idea to keep the names distinct so you dont mix them up
otherwise you will have a bunch of "Interact.cs" files in your tabs in your IDE and, how would you know which is which?
yea thats what im trying to say, but then i wouldnt have a fixed name for the class inside of it.
wait can i just have a filename class and a interact class
and just leave the filename class empty?
lets start from the top
whats your actual goal, high level result in like, video game terms from someone playing your game
alr
i want someone to click and interact with something theyre pointing at that is in the interactable layer
sounds good so far
whats the technical challenge you forsee, without talking about code yet but like, describing the problem in plain english
imagine you are trying to describe the problem to someone who doesnt know anything about C# yet
File and class names are decided at compile time. I don't understand what you mean by them not having "fixed name"?
can i draw a board and send it here
not beeing ironic or sarcastic, just makes it easier to explain
Im sure I will understand but, just give it a shot first at describing the technical challenge
Ok, that's easy. Just cast a ray at the scene, get a component that you want to interact with, and interact with it.
"I want to do x, but the challenge is y" etc etc
(I already have a pretty good guess as to your issue because its a very common one that gets asked in here multiple times per day, but its good to get into the zone/habit of articulating challenges this way)
alr, i need to send a ray from the camera in the direction that the camera is facing, if that ray hits something that is in the "interactable" layer it will get the interact script inside it and execute its "Interact()" function. but to get the interact script inside it i need the file name of the interact script(because you need to specify the variable(that stores the script so you can call its functions) type), but if i name all files the same(so i always know the file name), ill get a bunch of "InteractScript.cs"'s in my editor and i dont want that, also i'd have to separate the files in different folders bc there cant be two same named files in the same folder.
but to get the interact script inside it i need the file name of the interact script
You typically useGetComponent<T>()where T is a Type, not a filename
so i only need the name of the class(the class is a type)
The handy thing here is GetComponent works with Polymorphism and Encapsulation
whats that
something very important to read up on when it comes to C# and all forms of OOP
alr ig ill check it out
ok so basically polymorphism means it can get a component by it's parent class(classes like Collider, MonoBehaviour, etc.) right?
but the long and short of it is, lets say you have:
abstract class FruitEntity : MonoBehavior { ... }
and then you implement some classes that inherit from it:
class AppleEntity : FruitEntity { ... }
class BananaEntity : FruitEntity { ... }
If you put an Apple component on Object A, and Banana component on Object B, but if you use
otherObject.GetComponent<FruitEntity>();
It will work for both the Apple and Banana components, because they both are FruityEntitys
exactly yup
and now i realised i could be using class parenting to solve this issue
It's called inheritance
so i need to create a parent class(lets call it interact) that will have basic interacting functions and subclasses that inherit from that class and those will be singular to objects
ok
But you can't access the child variables or methods through getting it that way, unless they override the same methods. Just as something to be aware of
Thats one approach, but there also can be even easier ways to consider
yea thats what i was thinking
like what?
The next thing to consider:
All of these objects, do they have common functionality? You can have many instances of the same class, but they behave differently simply by modifying properties/fields on them. The code can be the same, but just changing configuration of them changes how they act
Which means just 1 single file and then you make prefabs with that 1 component applied, and you just modify parameters on it to change its behavior
You typically don't want to be dependent on specific behaviour of sub classes. You should be able to achieve specific behaviour by calling the base class methods/properties.
no im making wildly different mechanics like cutscene interactables to doors, but i can also just make a "type" variable on the interact script and that'll change the functionality
why tho? just good practice or performance issues?
thats valid, but perhaps you can still very much "categorize" them into a couple specific "types" or "behaviors"
To get the most out of it
like you may perhaps have hundreds of interactables... but you can group em up into a small handful of types of interactables
Good code structure. You want your code to be readable, extendable, debuggable.
Hardcoding complex systems makes them hard to maintain.
you mean using the same script for two interactables that have the same functionality?
makes sense
yeah like all pickups likely can have the same code with just params for what gets added to your inventory
and all your NPCs also likely can just use a single "NPC Interactable" class, and you just customize some properties on that to define the behavior, what they say, etc
makes sense, although im not handling pickups as interactables.
alr, tysm for the help
ill go finish my code now
fair enough, point being is to start by thinking about if you can simplify your problem space down to be a lot smaller and easier to work with
alr
i shouldve have thought of this solution earlier tho, as i was trying to identify all the colliders in an object by using GetComponent<Collider>(); which is basically the same thought process
also i couldve just used GetComponent<MonoBehaviour>() if i was trying to do 1st solution i suggested, but idk if the transform or other components are inheriting from monobehaviour as its a common class so its probably not a good idea to do that
Now in other news, Im trying to sit here and reason out a bit of a puzzle, and Im sort of unsure how to proceed.
I have a 8 way movement topdown tile turn based game where theres a few ways the player can interact with picking their next action to perform.
By default its just moving, and I highlight an A* path to where their mouse is hovering to show where the character will go if they click, if its a valid tile they can get to. Otherwise, no highlighting.
I also have the ability to click abilities with cooldowns, which will switch to instead highlighting "valid" tiles they can click to use the ability on (IE, they can use roll which rolls em 2 tiles in a direction they choose, or shoot a bow in 1 of 8 directions, etc etc)
So once ability is selected, its icon swaps to a cancel button to swap back to the default move mode.
And, while in ability mode if they hover over a valid tile it turns green of course.
I am trying to figure out a clean approach to sort of handling all these possibilities in 1 nice flow of logic for what tiles are highlighted vs not, and whether to swap to "okay stuff is happening now"
I have 2 methods on my UIService that already facilitate drawing tiles:
void ClearHighlights()void RedrawHighlights(Vector2Int origin, (Vector2Int Offset, HighlightColor Color)[] tiles)
So that part is solved, the second method draws the array of tiles with respect to the origin passed in as the first param
I am participating in sebastian lagues chess challenge, I am trying to implement move ordering with no success. The times for each move increase drastically when I have move ordering enabled. I believe I have done everything right (supposedly) with my algorithm. I cannot find any issues. Any help is greatly appreciated. Thanks
private Move[] OrderMoves(Move[] moves, Board board)
{
for (int i = 1; i < moves.Length; i++)
{
Move current = moves[i];
int j = i - 1;
while (j >= 0 && ScoreMove(moves[j], board) > ScoreMove(current, board))
{
moves[j + 1] = moves[j];
j--;
}
moves[j + 1] = current;
}
return moves;
}
private float ScoreMove(Move move, Board board) // Gives an estimated score of the move.
{
float score = 0f;
PieceType subject = board.GetPiece(move.StartSquare).PieceType;
PieceType target = board.GetPiece(move.TargetSquare).PieceType;
if (target != PieceType.None) score = pieceVals[(int)target] - pieceVals[(int)subject];
if (move.IsPromotion) score += pieceVals[(int)move.PromotionPieceType];
// Square is attacked by a pawn.
return score;
}
Now in other news Im trying to sit here
I am having a problem with cameras. I want to use the player to get in a car and then disable the player, resulting in the camera having to change angles from the player to the car. It throws me this error NullReferenceException: Object reference not set to an instance of an object. I have assigned all the correct values and objects in their referring scripts but it keeps showing it.
Here is the relevant code for the camera:
public void CurrentCameraLocation(CameraLocation newLocation)
{
if (newLocation == CameraLocation.Player)
{
player.SetActive(true);
transform.position = new Vector3(cameraPosPlayer.position.x, cameraPosPlayer.position.y, cameraPosPlayer.position.z);
}
else if (newLocation == CameraLocation.Car)
{
player.SetActive(false);
transform.position = new Vector3 (cameraPosCar.position.x, cameraPosCar.position.y, cameraPosCar.position.z);
}
cameraLocation = newLocation;
}```
Here is the relevant code for the car:
```cs
void Update()
{
if (rotate)
{
rb.freezeRotation = false;
}
else
{
rb.freezeRotation = true;
transform.position = startPosition;
}
}```
and here is the relevant code for the player:
```cs
void OnCollisionStay(Collision collision)
{
if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
{
cameraScript.cameraPosCar = getInCar.cameraPos;
getInCar.rotate = true;
changeToCar = true;
}
}```
You should send it to the community discord doing the challenge(last link in the readme): https://github.com/SebLague/Chess-Challenge#faq-and-troubleshooting
Actually it looks like you already are in the server
You can go send the code there 
Which line is it throwing the null reference exception for?
void OnCollisionStay(Collision collision)
{
if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
{
//38 cameraScript.cameraPosCar = getInCar.cameraPos; // this line here
getInCar.rotate = true;
changeToCar = true;
}
}```
I’ve asked for help multiple times there and have gotten no reply.
I’ve also asked for working code to analyze
Haven’t gotten any
I’ve looked at Sebastian’s himself and still can’t find what I’m doing wrong 😭
Which line is the error on though
cameraScript is null then
What would you suggest to fix it?
What gameobject is cameraScript attached to?
actually getting some help right now @buoyant crane thx tho
camera holder
it's an empty gameObj
Ok... and what about the script you showed us?
The camera script is placed on the camera holder
If you have a public field (or one with [SerializeField]) i would just drag it in throught the inspector.
the Car and Player script are placed on the parent of the objects (Both empty objects)
Otherwise you have to find it in the scene
[SerializeField] GameObject player;
[SerializeField] PlayerMovement playerMove;
[SerializeField] Transform cameraPosPlayer;
public Transform cameraPosCar;
public CameraLocation cameraLocation;
those are the variables
all dragged in place
Sorry got distracted, you have to debug why cameraScript is null
void OnCollisionStay(Collision collision)
{
if (collision.collider.gameObject.TryGetComponent<GetInCar>(out GetInCar getInCar) && Input.GetKeyDown(KeyCode.E))
{
//38 cameraScript.cameraPosCar = getInCar.cameraPos; // this line here
getInCar.rotate = true;
changeToCar = true;
}
}
I want to debug the highlited line
Wait, where are you getting the cameraScript variable from then?
And he means YOU debug it, in your ide and unity. Talking to people isn't debugging it
I feel confused
Use debug.log or even better, use breakpoints
why is one person helping me and one lecturing me?
You mean me? I'm helping, but ok, I'll stop
We’re both helping
ik, but it get's confusing when 2 people try to make differing points
cameraScript is the only thing that can be null in that line
which makes the one look like a lecturer
fair
I'm confused because we're saying the same things... but I get it can be confusing with more than one person, so I will stop responding. Good luck, truly
ah yes, that went over my head
thanks a lot
How do you initialize cameraScript in your code?
[SerializeField] CameraScript cameraScript;
Are you dragging in a reference?
Vector3 right = transform.TransformDirection(Vector3.right);
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);```
Hello, how do I fix an issue where the player moves faster diagonally? Above is my code attached to character controller
You need to get the movement direction vector and normalize it before multiplying by speed.
Of course, but this code is wrapping Netcode RPC calls so I definitely don't want it running every frame.
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
Vector3 normalizedMovement = (forward * curSpeedX + right * curSpeedY).normalized;
moveDirection = normalizedMovement * Mathf.Max(Mathf.Abs(curSpeedX), Mathf.Abs(curSpeedY));
moveDirection.y = movementDirectionY;```
Is this alright?
Is this all in update?
yup
- Instead of
TransformDirection, you can usetransform.forward/rightdirectly. - Not sure what that weird math is. You should get the input direction first from your input. Normalize it and then multiply by speed. I don't understand why you calculate movement separately for each axis..?
All you need is:
Vector2 input = new Vector2(xAxis, yAxis);
input.Normalize();
Vector3 movement = input * speed;
Ah, if you follow my example, you'll need to transform the vector into the object space in the end.
Trying to figure out the best way to make a list of unique values (enums) that can be serialized on the inspector for asset creation, which will also be read multiple times during runtime. The obvious answer you'd think would be a bitwise enum, but depending on the size of the enum, I'd have to loop over every bit to find all set bits before seeing if those keys exists in the dictionary. Any other suggestions?
ah alright I get it now ty
What's the problem of looping it?
Also, if you want to check a specific value, you can do bitwise & to see if it's included in the bitmask or not.
Right, actually all keys do exists in the dictionary, but depending what's in the list will be what events I trigger
so if I had all entries of my flag enum filled up, that's quite a lot of looping each time I check it
32 iterations at max. And you'd need to loop regardless. Even if it was an array or list of values.
I guess I could just onvalidate and cache the exact keys
Unless I'm misunderstanding your use case.
right, i have to loop regardless if it's a bitwise enum, but if I just had a list of value I'd know for sure what those values are and the it would just be a O(n) operation
I guess so. The tradeoff is between memory used and runtime complexity.🤷♂️
I just hate using onvalidate honestly but that's usually the fix to the editor's shortcomings
ah, hmm
Is there a way to do something when PlayableBehaviour starts? And I mean not when it's state becomes Playing, but when we reach it in the track. So basically do something on its first process frame.
Currently I check for whether the action has been taken. Is there anything built in for that? (OnGraphStart and OnBehaviourPlay don't work in that manner?)
Start() Awake()? 😄
Hey guys! My friend @magic island has a problem with this camera jitter/jumping. They already tried capping the FPS to 140 and 60 and changing Update() to FixedUpdate() and Time.deltaTime() to Time.fixedDeltaTime(). Both approaches didn't really solve the issue.
See video for what I mean, you can clearly see the jumping of the camera, even though we have lots of FPS / I move the mouse slowely.
PlayableBehaviour doesn't receive those messages
This kinda looks like performance spikes. Your friend needs to come here himself and share some profiling data.
And considering graph architecture it would trigger those the same time as GraphStart
Aight, they are looking at the profiler right now. Should they share a video or a picture?
A screenshot should be fine.
One note with the profiler, the "Deep Profiling" mode can help check where GC.Alloc calls may be coming from, which can often contribute to performance issues as well, but its not enabled by default
yeah there are some performance spikes
Yes, we have never used the profiler, so we don't really know how it works or what we have to look out for
granted, we've never encountered that camera issue
something certainly causes some performance spikes
It's very hard to see the numbers on mobile, but it doesn't look like the culprit.
Either there's something very weird with your camera controller, or it's something with your machine.
Machine shouldn't be the issue, since we have tried it on 4 different devices, all of them using different hardware
Is it okay to share the camera script in here?
That looks more like it.
Most of it seems to come from the editor loop.
Yes, if you follow the code sharing guidelines. But before that switch the profiler to editor mode and take another screenshot of a spike.
and profile an actual build too, to confirm you aren't chasing ghosts based on that last screenshot
If the render thread is any indication, it looks like you are playing some video in the scene?
Yes. there are some videos inside the building/scene, however, they only play once you get near them and the problem percists outside of the video zones.
it plays a lot of videos actually
ah right, you are right
On this frame it seems like it's waiting for something on the GPU thread.
That's the issue probably.
Playing videos is not a "child's play". It's a serious business. If you run several players at the same time, they're gonna do some awful stuff to you.
yeah i should implement some code to only play them when i am near them, hopefully that fixes the issue
Alright, so that works good enough. We only play and load one video at a time minus the preloading we do when the app starts up. The performance spikes are almost completely gone - they still happen when you go near a videoplayer, though. It's not noticable enough to consider it annoying now. Thanks @cosmic rain for the advice!
okay np
speed = Vector3.Distance(transform.position, lastpos) / Time.deltaTime;
lastpos = transform.position
this is giving me the result 0 every time
I've debugged it and for some stupid reason transform.position and lastpos returned the same value (i debugged it between the spieed calc and the last pos change)
Why?
There are no other instances where i change lastpos
is it in fixed update?
no
not strange, the issue is execution order
you are testing for transform change before it occured
i assume some other script moves the object
the same
are you moving it with physics?
I guess its because it calculates collisions
We need to see more of your code. It's totally not clear what you're doing from that snippet and where/what you debug.
Anyone knows a way to write at the start of a string? I need to add text above text in a string but I can't find anything on Google.
What did you google, because I find it very odd you cant find anything on google for this very common task
add text to the start of a string unity
tmp text inverse order
invert string order unity
All ive found is to put Line Spacing -1 but only works with old text not tmpro
And I just did it right with something I figured but its weird to not have something to reverse order in strings or texts
All you need to do is concat the string like
someVar.text = someString + someOtherString
Possibly with a \n in there
yeah i just did that, but i wanted something to just inverse
Although you should use stringbuilder instead of any string concat to avoid allocations
Heya
Inverse meaning reverse the string? Or something else
You could probably just get the char array and call Array.reverse in that case, not sure if theres a more optimal method
Bread
Chocolate
to
Chocolate
Bread
invert order
Maybe a for that goes on reverse
Then just concat bread at the end instead of the start.. not entirely sure what you want otherwise
or add the text to the start so it works the same for me
Why add it to the start and then try to invert, instead of just adding to the end
no no, its one thing or the other
i just needed one
im trying to make like a history of text written
and i want the newest at the start
but nvm i just did the concat of the previous history to the end so i add the new text at the beggining
Definitely use stringbuilder then
So i need help
float distance = Vector3.Distance(character.position, zombie.position);
if (distance < 10)
{
Vector3 direction = zombie.position - character.position;
Quaternion rotation = Quaternion.LookRotation(direction);
head.rotation = rotation;
rotation = Quaternion.Euler(character.eulerAngles.x, Mathf.Clamp(head.eulerAngles.y, character.eulerAngles.y-90, character.eulerAngles.y+90), character.eulerAngles.z);
head.rotation = rotation;
}
This is my current code, the goal is to look at the enemy when they're nearby
Problem is, at some angles, the head flips suddenly to the wrong direction
Hi is there a way to apply a shader to the Unity UI?
I have a canvas screen space, which I can't change to another space it has to stay in this one.
I can't find a way to get a colorblind shader applied to this UI in this space.
Because the canvas screen space UI looks like it's rendered outside of the unity pipeline.
I also try to create my own scriptable render pipeline, but even if you create a null one and all the render is black, the canvas screen space is render over all the previus render.
If I have a database of scriptable objects that contain object data, can I copy that SO class into an object in a smart way so that it's not a direct reference making me able to alter the SO variables without it reflecting on all other objects that use the same SO data?
I'm looking at ICloneable (https://learn.microsoft.com/en-us/dotnet/api/system.icloneable?view=net-7.0), do you think this would be appropriate??
Yeah i have use IClonable interface to do that, but some times i have problem with the child objetcs.
For example, it copy the data from a class, but if inside that class there is a member that have a direct reference, the direct reference will persist in your copy
Yeah I saw that when it came to deep vs shallow copy but that should be okay. I only need a shallow copy so I can alter a few variables. Thanks.
Seems doing Instantiate might be a better idea. Clone worked. I could alter the variables and read them separately on each object, but for some reason the original also got changed.
You should consider other pattern then copying a ScriptableObject.
why
Usually, you have something that represent the instance and something that represent concept.
By example, If I say: Give me X weapon, I'm talking about the concept. If I say give me the weapon of the player, I'm talking about the instance of the weapon.
Variable are different on both object.
In one situation, the variable is the same for every weapon that is associated with the given SO.
You can see this as the FlyWeight pattern.
nah the reason i want a shallow copy is because i am storing behavior scripts as SO's for plug and play behavior scripting, and I want the behavior itself to have local internal playtime and behavior stage tracking.
This is exactly what I am doing currently and it does not work well. Instead, use something like what Unity has done with Visual Scripting.
if (Input.GetKey(KeyCode.C))
{
cam.transform.localPosition = new Vector3(cam.transform.localPosition.x, -2.5f, cam.transform.localPosition.z);
gameObject.transform.localScale = new Vector3(1, 0.5f, 1);
GetComponentInChildren<CapsuleCollider>().height = (3.089386f / 3);
speed = 5 + SpeedBoost;
SoundLevel = 25;
}
else
{
if(!Physics.Raycast(transform.position, new Vector3(0, 1)))
{
GetComponentInChildren<CapsuleCollider>().height = (3.089386f);
gameObject.transform.localScale = new Vector3(1, 1, 1);
if (FB != 0)
{
cam.transform.eulerAngles = new Vector3(cam.transform.eulerAngles.x, cam.transform.eulerAngles.y, Mathf.Sin(TimerBob));
}
else
{
cam.transform.localPosition = new Vector3(0, (Mathf.Sin(TimerBreathe) * 0.13f), 0);
SoundLevel = 35;
}
}
}
(Code for @naive swallow )
somethings definitely happening becase the headbob and idle bob stop
I'm on mobile so reading that code is not really in the cards for me at the moment, but maybe pose the question again here and see if anyone else can assist
how do i calculate the amount of torque needed to reach a certain rotation?
p.s. using rigidbodies
and door hinges
hi
I want to access a script from a prefab (public cannon cannonScr;), but it doesn't appear when I want to integrate it in the Unity inspector. Do I need to do it differently with prefabs?
is your prefab in scene?
try getcomponent?
??
object in scene cannot reference script of prefab in folder but you can use get component to get its script when instantiate
or you have tried but it doesnt work
idk who to do this
i mean with a script
the fact is that i Instantiate a prefab and i want get a var from anotehr script
you mean the spawner want to access some scripts on prefab? or another script not on the prefabs (on other gameObject)?
the boject i spawn (the bullet) i want to get a var from the gun scr
@hidden gulch
I'm not exactly sure, but maybe Kinematic Equations can help you.
You could also divide the amount of rotation by the amount of time you want it to take to get the needed per-frame rotation value, but idk if that's working properly with Rigidbody
alr, ill take a look at that.
oh so the prefab wants to access the variables on spawner script
declare a property on bullet's script and the gun pass its script to it
instantiate().getcomponet<>().gun script=this
idk if im doing it bad but it doesnt work
@eager wagon
Could you show some code?
yep
GameObject cannonBallInstanciada = Instantiate(cannonBall, transform.position, Quaternion.identity).GetComponent<>()cannon.angles;
i trieed to replicate this
instantiate().getcomponet<>().gun script=this
Bro wtf is GetComponent<>()cannon 😄
That other person wrote some pseudo-code, you gotta make it fit for your project.
At this point, I think you're better off in the beginner channel!
someObject.GetComponent<SomeComponent>().someProperty = someValue;
Pseudo-Code, don't copy paste this, modify it accordingly!
https://m.youtube.com/watch?v=jGD0vn-QIkg&pp=ygUJQyMgYmFzaWNz
Let's write our first code in C#!
► SIGN UP FOR JASON'S COURSES: https://game.courses/gamearch/
● Watch the Getting Started Video: https://youtu.be/N775KsWQVkw
● My Solution to the Challenge: https://forum.brackeys.com/discussion/746/brackeys-solution-to-c-tutorial-01-challenge
https://forum.brackeys.com/discussion/746/brackeys-answer-to-c-tu...
yes but whats the way to get a variable when i Instantiate a object
var theObject = Instantiate(...)
theObject.theVariable = ...
Still, pseudo-code, don't copy paste.
But seriously, watch some Videos and move to Beginner
you already referenced to the object have you spawned so you can getcomponent on it
brackys c# tutorials are dumpster fire
@rigid island
Brackeys sucks.
But for someone who's mindlessly copying and pasting, it's enough to learn the basics!
why link it lol
Why not give some useful advice to this person instead of questioning mine?
You shouldn't complain about answers while you're not giving any on yourself!!
It's not about the specific Content Creator, it's about the severe need of learning the very basics, if you write something like GetComponent<>()cannon.angle you can pretty much watch Brackeys to improve.
Just search for C# Basics and there are probably 20 more people teaching them, choose whom you like.
And still, #💻┃code-beginner
To be absolutely fair, if you're learning C#, do it outside of a Unity Context and come back to Unity once you grasped the fundamentals, it'll click much much faster for you this way, else you'll probably jump from one Tutorial to the next one, hoping that they'll complete the game on their own, which they won't.
will simplify the question cos i think u dont underestand me.
i have a gun. the gun can create bullets. the bullet spd is a var from the gun. i want get the scr of the gun like this: public cannon cannon;
teh problem is that when i try to put the script in the unity inspector i cant (cos teh bullet is a prefab i underestand). So now this guy told me that i can modify a variable when i Instantiate the object.
the way u told me aint working for me, since when i try to TheObject.var it doesnt works
my friend, please just watch some C# tutorials, you'll thank me in the long run 🙂
It's not my job to solve your problems, it's nobodies job, it's our job to guide you towards the correct direction and give you some advice, which I did in the best possible way.
If you're going to accept it or not, that's on your side.
One more pseudo for you:
void ShootBullet()
{
var bullet = Instantiate(...)
bullet.speed = this.bulletSpeed
}
Tbh, IMO, you shouldn't get any more responses in THIS channel, at least take it to Beginner and admit that this is what you are.
You seemingly don't want to learn, you want us to give you the solution.
@n.navarone just stop bothering, this person doesn't want to understand, and we're wasting time and energy here
you have to have some basic understanding about accessing variables in scripts
you can't just skip the basics
man pls i studied programming for 2 years dont disrespect me like this
whatever it was, it was not C# so that knowledge is irrelevant
i wached a 127 vidios tutorial before this
you need a structure course,not random vids
the solution is you learning the basics
you were given a solution, because you don't understand the basics you don't understand the soltion..
you just want to be spoonfed which is not ok.
you should learn some basic stuff first
quick question:
BehindWoods = new List<GameObject>(AheadWoods);
this assigns BehindWoods to a new list and then fills the list with the contents of AheadWoods, correct?
yes
great
Yes, but I am not sure if it'll reference the original AheadWoods or if it's copying them (in case it's a reference type)
it will not deep copy i think,
i have to check the source code
the source code....
there should be no generic solution to deep copy something
what does deep copy mean?
deep copy means it creates a new object based on the copy but it's entirely new object
shallow copy means it copies the object but still holds the same references
which means if I change the original, I will change the copy?
Or no
a shallow copy would
unfortunate
might be worth a read
https://code-maze.com/csharp-how-to-clone-a-list/
there is also AddRange
maybe
basically what im trying to do is a staggered moving of a bunch of objects
WaitToMoveTarg += Time.deltaTime;
if (!IsVis)
{
awaitWoodMove += Time.deltaTime;
}
if(WaitToMoveTarg> 8)
{
if (BehindWoods.Count > 0 && awaitWoodMove > 0.8f)
{
var moveWood = BehindWoods[Random.Range(0, BehindWoods.Count)];
BehindWoods.Remove(moveWood);
AheadWoods.Add(moveWood);
MoveWood(moveWood);
}
else
{
BehindWoods = new List<GameObject>(AheadWoods);
AheadWoods = new List<GameObject>();
Orient.transform.position = Target;
}
}
this is the code rn
Still having this issue, anyone encountered this before and know how to fix it?
#archived-code-general message
can one audiosource overlap with itself or does it start over if you play it again while its playing
iirc Play() will reset / PlayOneShot overlaps
woah
time to replace
all of play with playoneshot
no bad outcomes will come of this im sure
oh wait its funky and different
ill figure it out
i don't really know the specific keywords/terms i have to search up to make this but how would i be able to create a circle of buttons that rotate when you cycle through them
like the mario and luigi system
pseudo 3d in 2d, or actually 3d?
pseudo 3d if that works
prolly would be fine to slerp both its translation to the next spot, while also slerping its scale
Is there a way I can go without allocating garbage here
meshRenderer.materials = newMaterials.ToArray();
The new material list can vary in length and id prefer to use an array + count variable
Profiler shows .ToArray() is allocating garbage
Though you'll need the ones going "back" to slerp the opposite way to the ones going "forward"
that entirely depends on how you are building that list of new materials
the only thing you can do is initially use an array
But effectively what you need is to just know how big the array is gonna be before you start filling it and you are golden
Makes sense, that was my original approach and I just made it 256 in length but that KILLED performance super badly
even though I only need 3 ish elements right now
never tried something like that, interesting
it allocated 0 garbage but was bad lol
guess it attempts to create new submesh groups for each index
anyway, just do ToArray() once
its not garbage if it doesnt get collected
Its the only part of my code which allocates garbage every time a chunk is modified
I could switch to advanced mesh api later on probably but its performant as is
i guess you update materials based on what voxels chunk has?
Thats what I'm doing, ill just paste the method
List<Material> newMaterials = new List<Material>();
private void UpdateMesh() {
thisMesh.indexFormat = IndexFormat.UInt32;
thisMesh.Clear();
thisMesh.subMeshCount = 0;
colliderMesh.Clear();
// Apply vertices
thisMesh.SetVertices(vertexArray, 0, vertexCount);
colliderMesh.SetVertices(colliderVertices, 0, colliderVertexCount);
colliderMesh.SetTriangles(colliderTriangles, 0, colliderTriangleCount, 0);
// Grab appropriate materials for submeshes
newMaterials.Clear();
for(int i=0; i<trianglePartitions.Length; i++) {
if(trianglePartitions[i].capacity > 0) {
thisMesh.subMeshCount++;
newMaterials.Add(BlockDataManager.Instance.blockMaterials[(BlockType)i]);
thisMesh.SetTriangles(triangleArray, trianglePartitions[i].start, trianglePartitions[i].DataLength(), thisMesh.subMeshCount-1, false);
}
}
meshRenderer.materials = newMaterials.ToArray();
thisMesh.RecalculateNormals(UnityEngine.Rendering.MeshUpdateFlags.DontValidateIndices);
meshCollider.sharedMesh = colliderMesh;
}
I have a giant array for triangles that i split into partitions
so each material starts at its own index and has a capacity in the triangle array, thats what the for loop is for
It seems like the physX calculations with mesh collider is the biggest chunk of performance now but it works fine for now
you can completely avoid using multiple materials
if you use a shader tilemap shader or texture3d
Ah as opposed to using one sprite sheet and splitting the UV up?
I'm not using any textures right now, deciding on how i want to do things
all cube faces have same uv
you "paint" them with indexed color
each R value 0-255 represents an index in the atlas
shader selects that index with frac
you are offseting uvs on the shader
Oh i see, i could probably do some blending between types with that as well?
I remember the game cube world had some pretty gradients