#archived-code-general
1 messages · Page 162 of 1
nah, it's good when it yells at you
haha
that's what it's there for
I am joking
although it can be very confusing to see that error
alright let me try that out
I'm trying to create a melee system for my topdown 2d game , but the common way of just creating an overlap circle doesn't feel right cause it just checks for 1 frame ,not the whole duration ,I have an idea but I want to hear from others too
well nothing is stopping you from doing that query every frame during the duration
you check for the whole duration by checking every frame!
that was my idea but how do I make the enemy not get hit a million times
You can track which colliders you already hit during the current attack and ignore them in subsequent calls
I frames could work right?
that too yes
ic
that's what I do
(even though I use collision events)
works the same for both collision events and overlap queries
I'll probably go with your method
I feel smart when my methods work even if they barely do 💀
Hi i am trying to make my cinemachine camera follow an instantiated prefab but i keep getting this error
This is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class PlayerFollow : MonoBehaviour
{
public GameObject Player;
public Transform FollowTarget;
private CinemachineVirtualCamera vcam;
void Start()
{
var vcam = GetComponent<CinemachineVirtualCamera>();
}
void Update()
{
if (Player == null)
{
Player = GameObject.FindWithTag("Player");
}
FollowTarget = Player.transform;
Debug.Log($"target = {FollowTarget}");
vcam.LookAt = FollowTarget;
vcam.Follow = FollowTarget;
}
}
i actually have the same issue
!code
📃 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.
the way i fixed it was attaching a camera to a prefab
so the prefab contained both the prefab and the camera
Error states that the issue happens on line 26.
you defined a local variable in Start:
var vcam = GetComponent<CinemachineVirtualCamera>();
so your vcam variable is never actually assigned
get rid of var there
this is actually 100% the correct cinemachine way to do it btw
oh thank you that helped
is there a way ard it actually? or if u want a custom camera u just assign the priority during runtime
NavMesh won't be created even though I have everything turned on in Gizmos and have set all of the ground to the Walkable layer
doesn't it need a collider?
i don't use navmesh so im guessing
where's the navmesh surface?
2020.3.20f1, personal license running on DirectX 11
no
what version of the ai navigation package
You should probably show the navigation tab and what did you set ground obj as
These cutoff screenshots aren’t helpful
Ok you hit bake in the bake tab after ?
yes
Does baseground have the collider too ? What other settings did you touch
I set all of the baseground to the Walkable layer
The game object layer here is inconsequential
The important part is it’s marked as navigation static and it’s as Walkable navsurface mask inside the object tab of navigation which seems to be set
hmm
Let me see gizmos for the box collider
is there a way to tile trajectory line sprite along its local y axis
if i have a list with different gameobjects, and I want to activate a random number of them but checking the index so im not activating the same object its recommended to use a "while" ?
Like this for example
randomIndex = Random.Range(0, src_implantes.Count);
prevrandom = randomIndex;
src_implantes[randomIndex].SetActive(true);
sol_implantes[randomIndex].SetActive(true);
src_Itemhardware[randomIndex].SetActive(true);
sol_Itemhardware[randomIndex].SetActive(true);
randomIndex = Random.Range(0, src_implantes.Count);
while (randomIndex == prevrandom)
{
randomIndex = Random.Range(0, src_implantes.Count);
}
src_implantes[randomIndex].SetActive(true);
sol_implantes[randomIndex].SetActive(true);
src_Itemhardware[randomIndex].SetActive(true);
sol_Itemhardware[randomIndex].SetActive(true);
you could sort the list in a random order, take the first X elements and apply your logic to those
pick a random number P, from 0 - count of the list
shuffle the list
activate the first P elements of the shuffled list
I have a first person shooter, and I want to display a "threat indicator" on the screen for enemies that are close to the player, but not visible (behind the player). I have no clue how to start, can someone give me a tip how to get started? (I'll figure it out as I go)
this type of threat indicator is often seen in space shooters like freelancer or elite dangerous
Actually I just figured it out I think... physics.sphereoverlap or whatever the function is called, get the distance and direction and then draw it on the UI with a normalized distance from the middle of the screen
How would that indicator look like, visually?
Kind of like the damage indicators in most FPS games, where there's an arrow that rotates around the center of the screen to show where it came from?
exactly
Yeah so just like you said. The difficult part is just translating the direction (in 3D) to your screen (in 2D, and rotated to face the screen)
Is it really that tall or just screenshot?
It's really that tall
Why
let me make it all over again
Nothing vector math can't solve, probably with a ProjectOnPlane to flatten the direction down relative to your ship's orientation
It should be max height as ground
wdym?
It’s floor right? Why is it taller than the buildings
@surreal valve Make a thread so we don’t flood chat
I have no idea how that happenes
It not code question #archived-lighting
Probably not because of your code
ok sorry
Can someone explain in simple terms what Vector3.ProjectOnPlane does? Shouldn’t it return a plane object or something?
the heck is that? never heard of it
It "flattens" a vector on the plane that has a specific normal
Vector3 Vector3.ProjectOnPlane(vector, normal)
Red original, blue projected, normal not visible here, but should be vertical
third person angled down camera, you want the character to move forward along the ground in the direction the camera is facing
that's a super common example
wall running
makes sense
Like, on a slope
lots and lots and lots of uses
Is the normal not the dotted line? Or would it retain the original normal?
It's a vector that would be parallel to that line yes, but pointing up
Ok, thanks, that makes sense
(the dotted line is not a vector per se in this image)
Yeah, without the arrow, there is no direction, only magnitude. That makes it really clear, thank you
My character always floats slightly above the ground, it's always elevated by 0.41 for some reason
Is your ground by chance exactly at 0? And is this even a problem
check the bounds of your collider
probably your animator
alr
yeah, two options
one: your character controller is too tall
two: your animations are pushing you a little above your rest pose
so it looks good before the game starts, then floats upwards a bit
yeah
It’d be good for adjusting my character to a free look cameras forward vector yeah?
And thank you
Yeah that's one of the numerous use cases of that method
Normal would be transform.up yeah?
Depends, in your case and in the image yes
it conastantly stays at 0.43y regardless of animation state
iirc, as long as at least one animation controls something, then the animator will always control that something
Thank you 🙏 the Unity explanation hurt my soul
e.g. the position
the normal depends what side you're in contact with. Its better to think of it as just a line coming straight out of the wall, since transform.up depends on rotation
I disabled the animator and this still happens
How can you check if a gameobject from my list of child gameobjects collides with another object?
in 3D, you can't easily ask if one specific collider is overlapping another specific collider
It would be like transform.LookAt(Vector3.ProjectOnPlane(Camera.main.transform.forward, transform.up)); yeah?
transform.rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(Camera.main.transform.forward, transform.up), transform.up);
If this object is rotated, it'll flatten towards its local up. Use Vector3.up for global up
in order to use this shuffle function i need to create a script with a static class?
public static void Shuffle<T>(this IList<T> ts)
{
var count = ts.Count;
var last = count - 1;
for (var i = 0; i < last; ++i)
{
var r = UnityEngine.Random.Range(i, count);
var tmp = ts[i];
ts[i] = ts[r];
ts[r] = tmp;
}
}```
I've got a cell fractured object. All those cells are put into a list. I shoot those cells one by one at the player. That works all, now I just have to detect if a cell collides with the player
Yes, that's a requirement for extension methods like these.
thanks, im new with the static term
ah, sure: just put a component on each object that responds to collision events
the component can do something in response to the collision, or tell something else about the event
my character's Y axis is always set to 0.43 (still happens with the Animator disabled)
So specifically, do you mean I make a script that checks if it collides and put that on every child object?
Right.
Alright
If they're still children, you could also put a Rigidbody on the parent. It will then receive all of the collision events from any child colliders.
Not sure if that meshes with your design tho
Can you explain why we use that method versus LookAt
That wont work, the parent is just a empty gameobject so it doesn't collide with anything. But thanks for help though
LookAt requires a position or object to look at
you have a direction to look in
position vs direciton
Ohhhh that makes a lot of sense!
It may be related to your ground check or collider then, I would also look at both of those in the Scene view
the type system can't save you there, since positions and directions are both Vector3's
Does anyone know how to fix this?
well, you've got those giant first person components too
i have no idea what they do
mostly postprocessing
Wasn't that
any idea about how can i modify this to shuffle 2 list equally?
Your collider is perfectly leveled with the ground, and your ground check logic is not passing your collider?
no
it's an extension method
you can just do myList.Shuffle(); when you have this
oh yeah sorry - you need a static class to put the extension method in
Yes
yeah thats solved, now I need to figure out how to shuffle 2 list equally
why do you need that
do you have pairs of items?
if so, you could always make a List<Tuple<Foo, Bar>> and shuffle that up
just something to note, you can use tuple deconstruction now to save a bit of code
(ts[i], ts[r]) = (ts[r], ts[i])
you're obsessed with this lmfao
hey its an awesome new feature a lotta folks dont know about :3
It's definitely a cute way to swap two values!
(x, y) = (y, x);
whichis exactly what you're doing
🤦
I also am so hype to learn that you can static overload deconstruction, so now I have this static function and its just so slick looking, so much easier to maintain/read some of this stuff:
public static Direction ToDirection(this Vector2Int vector)
{
return vector switch
{
( < 0, > 0) => Direction.DownLeft,
( < 0, 0) => Direction.Left,
( < 0, < 0) => Direction.UpLeft,
( 0, < 0) => Direction.Up,
( > 0, < 0) => Direction.UpRight,
( > 0, 0) => Direction.Right,
( > 0, > 0) => Direction.DownRight,
( 0, > 0) => Direction.Down,
_ => throw new ArgumentOutOfRangeException(nameof(vector), vector, null)
};
}
I was trying to figure out if there was a clean way to do it with math
but switch statements run like 20x faster no matter what I tried
it's probably true
that switches are faster
but my brain demands the math solution!
I always do it like:
Convert the V2 to an angle around the z axis.
Divide it by (360/8)
round to int (or ceil, or floor)
that gives you a number 0-7 for which segment it's in.
Which can be casted to the enum
your way is almost certainly faster
If you disable your first person controller, does the value stay at 0? If the script is on, are you able to manually drag it to 0?
I fixed it, sorry for not telling you
So I saw iOS doesn’t allow reflection in applications? If this is true how does Unity run on iOS devices?
It probably bakes the reflection data in at build time
you can't use code generation, so some generic stuff doesn't work in C# reflection, but generally unity bakes everything when you build with il2cpp
is it possible to use the Animation component to make simple sprite animations? I've found this is only possible using the Animator + a controller
I guess you could design the systems in that way, though I imagine that breaks a lot of custom reflection?
like you can't generate any new types at runtime by putting together generic types with new params
sure - the only difference between ANimation and Animator is how the states are navigated and blended
it's still using animation clips
Ah, so generation won’t work, but baking meta data lookups would? I am just getting into AoT code generation instead of reflection so ultimately won’t be an issue, just want to know what to avoid with reflection lol
yeah, you can access properties and fields, invoke methods and stuff like normal on any il2cpp platform - you just have to make sure the methods you want are included in the link.xml file or they might get stripped if they aren't explicitly referenced by actual code
or use preserve attributes or whatever you prefer
Great note thanks!
is there any way i can improve the responsivity of an accelerometer?
if (Input.acceleration.x > 0.4f) inputManager.SwitchLane(LaneDirection.Right);
else if (Input.acceleration.x < -0.4f) inputManager.SwitchLane(LaneDirection.Left);```I'm using this to detect tilting in my mobile game because the gyroscope was too weird
but it takes a good second for the game to realize my phone is tilted before it responds
my animation isn't playing
that's kinda how it works. You're basically on the same level as the phone autorotation now, which always takes a second
gyro is probably more responsive
it was working as intended previously when i had fire_animation switched off legacy and part of a controller
is there an easy way to get a cube object with each side as a different color
i just need a test material for orientation purposes
With probuilder either create a cube using it or probuilderize one then change the materal (or vertex color) of each face
Im getting error CS0111 for all of the methods in a script, and CS0101 for the whole class.
You have duplicated your script
I've looked and cant find where
make sure you're searching the whole project
it can be anywhere in your assets folder
This error occured after I tried to fetch a value from PlayerScript into another script
Make sure you're hitting Shift yes. Without shift, it searches the current file only
i mean none of that really matters - you have a duplicate script. Doesn't matter what you're doing in it
If the global find from your IDE didn't find two, you might need to get it configured
!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.
An attempt to find stuff in a project that's not loaded won't yield proper results
does anyone have a solution to jittery npc movement for navmesh.setDestination? I already have an invokerepeating which calls navmesh.setDestination(player) every half a second and that seemed to fix some of the jitter but there's still some leftover.
Aight, this is the part I am trying to figure out an appropriate way to handle, because Im tryin to think in my head the math for it and I am unsure how to approach it:
var roundTime = roundQueue.Max(q => q.Value.Sum(a => a.MinTime));
if (roundTime < Constants.MinRoundTime)
{
roundTime = Constants.MinRoundTime;
}
foreach (var (id, entityQueue) in roundQueue)
{
}
For all intents and purposes, roundTime is a float in seconds for how long the round needs to be, and roundQueue is a list of floats of min times for a given entity.
I need to normalize the times up such that the sum of the actions is equal to roundTime, but all of them must be greater than or equal to their original times
there shouldn't be any jittery movement unless you did something weird.
InvokeRepeating to set the destination is strange
invokerepeating to set the destination is not strange its so its not updating every frame or fixedupdate time
float totalTime = roundQueue.Sum();
float scale = 1;
if (totalTime > 0 && totalTime < roundTime) {
scale = roundTime / totalTime;
}```
now you can multuply all the times by scale to scale them up
totalTime can be zero D:
yeh, Im trying to puzzle that one atm, like what does that actually mean
I guess it's like... the round takes 10 seconds. If there's 2 actions in the queue that normally take 1 second each, you want to scale them up to 5 seconds each
nah cause scale wont work if they have a time of zero total, they instead need to be hard set up to the value but it could be a list so I need to evenly divide
but if they already add up to more than 10 it;'s unclear what they want
but if I have
0, 0, 0
and the round is 6s, then they need to become
2, 2, 2
but 0 * anything is 0 D:
seems like a degenerate case
yeah but actually a very common one
nah lots of the actions have no minimum time on em
oh sorry I actually - didn't realize you're the OP here lol
the min time means "This is the slowest this can go allowable" but some of them are totally fine with being a zero frame "instant" action (IE idling)
I could I guess instead have "zero" actually be 0.01f or something very smol
yeah for the purposes of this calculation you should give them some token small duration
yeah that works I think, shouldnt impact performance and keeps this logic easy to maintain
Ill just add a manual >0 check in the struct for sanity to make sure I dont forget in the future
@leaden ice I have a big chunk of my logic
... lol enter button, derp, sec
I have a big chunk of my logic I think I wanna break out a sub service, this one class is getting a bit too big.
The parent service is currently RoundsProcessService and its job is to do the whole "Given n player actions queued, process and start a coroutine for all entities actions for the next n rounds"
The logic is atm as such, all in 1 class (in terms of nesting, so 2 is inside of 1 etc):
- Process all the actions for all entities for all the rounds
- Process all the actions for all the entities for 1 round n
- Process all the actions for all the entities for 1 round, but differentiating between Pre/Post round (to handle that entities can have "haste" and move before the others do)
- Process the actions for 1 individual entity for 1 pre/post round
I have all this in 1 monolithic class atm and wanna break it down a bit cuz its getting unweildy... but struggling to think of like... what would I name these modules as I go down A- > B -> C
I feel like its 3 layers I can go with?
- All of the rounds for all entities and start coroutine
- All the entities but 1 round
- The actions of 1 entity for 1 round
I've been playing around with this volumetric fog thing from github: https://github.com/SiiMeR/unity-volumetric-fog
It's been working pretty well in play mode for quite a while now but it stops working once I make a build, without errors.
Any suggestions on how I could approach this problem?
partially solved
https://gist.github.com/SpawnCampGames/c633aa243404f482ece4e63b3ea3b007
hello, I'm working on my save system. so far so good and it works (i think) how it should..
only im having issues with naming the functions in a way that makes sense to me.. any suggestions on naming/ structuring?
how do you plan to populate _saveData here?
I think you'll quickly run into an issue here, where you are saving to one file only which will overwrite all data. This means that all the data you want to save has to be loaded or attempted to be found, or you'll lose some.
Ex: You want to save the position of every npc, lets just assume some destroy for whatever reason but can respawn. (Ik in reality you dont have to destroy them). You may run into issues that npcs arent in the game, so you either load the save data and modify each field specifically, or overwrite the file and lose data about some npcs. This example becomes quite apparent when you try to save other things, like npc location and idk some user settings. What if the npcs arent loaded while the user is changing settings
I imported an old asset pack and it broke my previously fine project. What do I do?
wel, so far i only have the player transform to deal with
public class SaveData{
public PlayerTransform PlayerTransform = new PlayerTransform
{
pos = Vector3.zero,
scale = Vector3.one,
rotation = Quaternion.identity
};
public bool FirstTimeLaunch = false;
}
[System.Serializable]
public struct PlayerTransform{
public Vector3 pos;
public Vector3 scale;
public Quaternion rotation;
}
ofc these all get created when i initialize the save data which is the FetchSaveData() function in the save manager..
which was called 'InitializeSaveData' first..
😅 just soo much going on, and the naming had me confused for a while.. when i went back to try to use it
if ur not using version control and u cant go back to a previous version, either just delete the asset back out of the project, or go in and fix the errors one by one from the asset
bawsi, atm im just going to do players positions and probably a checkpoint index
private void Awake() {
if (Instance != null && Instance != this) {
Debug.LogError("GameManager Instance already exists, destroying this object");
Destroy(this.gameObject);
} else {
Instance = this;
}
// this part bugs me... why would i be saving and creating a save file every single scene load?
// Event Fires When Any Scene Loads
SceneManager.sceneLoaded += HandleSceneLoad;
}
private void HandleSceneLoad(Scene scene, LoadSceneMode mode) {
InitializeScene();
}
private void InitializeScene() {
// should always be called first
// why? should this always be called first
this.SaveManager.FetchSaveData();
GrabReferences();
//we'll call this to grab each new inventory manager
//player health //or anything else we need to save
}
this is my gamemanager script and the only place i access the SaveManager (for now)
someone tutored me while making it.. and they made it more robust than i think my use-case will be
some suggestions
- Make the save manager a singleton, just to ensure theres no shenanigans going on with 2 instances ever. Id maybe go as far as throwing an error if 2 exist
- implement some interface so you can have different types of save data, and each save data just returns an object of what to actually store.
https://gdl.space/talutihara.cs this is what i use, its kinda iffy since I have to implement ToSaveable and SaveData but I just dont care to rewrite it at the moment. Each class that wants to save anything just implements the ISaveable interface and handles what the object actually contains. Since this logic is inside the class you want, you already know what the types are - save to different files for different data to avoid the case of loading ALL data previously written just so you can adjust 1 field
oh nice, thanks for the insight, i'll look into all this
in the interface u can see i define a key, thats how i separate the data into new files
i was wondering how i was going to do that.. tbh
u can customize the key in each class which implements the interface, but i like it when the key is the same as the file name
b/c im working on my main menu..
so the first thing imma run into is the Game Settings..
someone mentioned i should seperate these out from the actual gameplay data.. like player position, checkpoint etc..
and it sounds ur suggesting the same
yea u dont really need to have 1 file, id say the only benefit was if you wanted to make some load system where players can save multiple versions
then load whatever one they want, which you really only see in a few big AAA games
ya, i thought about slots but i finally decided against that for now until i learn more.
so for now i was going to either u continue off where u left or u start a new game / new save
so we have settings -> and then Play -> using those settings in a new save file
if u go back to main menu, it'll populate the settings screen w/ the settings u have modified.. or default if u havent
OH i remember why i wrote my interface to have both a ToSaveable and SaveData, it was because I can call SaveData() on the class itself, which right now just calls saveManager.Save(this); Otherwise id have to pass in the object to save and the key.
With my current implementation I just send the instance to the save manager so it can directly get the key by itself
yea something like this is really tedious to make if its not 1 file
i think im on the right path, its just all the names im using are soo similar i get confused
but i think making the save manager a singleton will help alot
atm, the gamemanager references it and the gamemanager is a singleton.. but by having it be its own singleton i can directly call my save function from it and not have to worry about going thru the game manage.r.
thats a start atleast 😅
yea the singleton really is just so you can get the reference without any weird inspector serialization or jumping through hoops
but it also makes sense to be one so double win
mmhmm, well u gave me some stuff to think about, thnks, still gnna try to name some things better.. and write out some better summaries and stuff
but i already feel a bit better about it ;D lol
lol ill be honest i rarely write good summaries, i was just looking through some code where i actually commented what most variables were for and it felt like i didnt write any of this
who snuck into my repository and wrote these comments?!
me neither.. but im glad i use em for this atleast
How difficult is to weld vertexes of different meshes together in Unity? As an automated editor before being built thing?
I am working on a lego-like brick system and am realizing it will be much easier to scope if I could leave holes in the meshes where I could generate the variants of various combinations, but I have never attempted to create a new mesh like that before
Things I imagine I will have to account for are the smoothing groups / normals / surface info making sure there's no obvious seams in the mesh?
why does this code shoot correctly at the mouse position but for some reason when i turn to the right it shoots back at the camera. https://gdl.space/orutixinof.cs
Any help would be appriciated
say i have this navmesh. the red capsule is the AI, and the blue capsule is the player (target).
If i try to pathfind from the AI to the target, it won't give me a partial or invalid path. no. it decides that going at the edge is perfectly fine and exactly what i asked for, and gives me a pathcompleted status. is there any way to stop that? I've been checking every function and forum and i can't really find a way? my only way right now is to ask here, or make my own pathfinding.
also, the agent doesn't have a jump height or anything like that, that would allow for it to cross the gap. there is also no link
have u tried with NavMesh.CalculatePath() or maybe https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
Might be a bit of a stupid question but is there any way to only set public variables in the class script itself and stop them from having them be set in the inspector for every script of the same class
u can assign public variables with code.. just as you would private variables..
Yeah I know but some I want dragged in
well drag those in
if ur saying u want the scripts to run the same whether uve assigned them or not
u can always wrap ur functions in conditionals checking if the variable is null
Ah ok
Thought there may be an easier way to only have some things show in the inspector of derivative classes but guess I'll just do that
yep, tried calculatepath(), but i'm not sure how i would go on about sample position?
public GameObject myVariable;
// Add other public variables here as needed.
private void Start()
{
// Check if the variable is assigned.
if (myVariable != null)
{
// Use the variable for something.
// For example, let's print its name:
Debug.Log("myVariable is assigned. Name: " + myVariable.name);
}
}```
then the code could still work on something that doesnt have myVariable for example
and calculatepath returned a valid path?
yep, as i said, it will take the nearest position that it can get, which is on the edge of that opening
and therefore it's a valid path
rather than actually using the destination i wish for it to use
hmm.. does stopping distance of the agent matter any?
it might be so high that its a valid location
close enuff
it's 1, and that distance is at least 5 meters. i did consider this anyways though, and made it as far as away as i could
and still worked
unity is smart pants and re-selects the destination to be the closest one
found forums with the same issue as mine
but not really any fix
atp i might just make my own navigation system
fun fact: if u open the navigation panel and select ur agent.. u can see gizmos of its pathing and stuff in the editor
may be helpful while ur debuggin this issue
A* is a good pathing alternative if u go that route
welp again, it's not much that i can do? the only way i can fix this is by checking if the destination is reachable through custom ways
very strange occurance ur having
when i get a free minute ill set up a test scene and see if i can replicate it
yeah the only problem is actually doing the navmesh honestly
i can't find much documentation on how to generate one
or i mean there is, but it's hard to follow
so it's gonna take a while
okay, thank you
oh yea i see something about Partial pathfinding
fun fact but unity's NavMesh uses A*
says u cant turn it off but u can write scripting to handle it
so perhaps u can find a solution w/o having to write ur own pathfinding
it's a thing, yes. it returns a pathstatus of "partial" if that happens
problem: this doesn't happen in this case
it genuinely returns pathcomplete
Unity says that the object reference isn't to an instance of an object on Line 56 (I did add the animator to the object)
ya, i cant say as to why that happens.. i would totally assume it would return partial
i did too 😭 but i guess not
and im pretty sure ur Destination is accurate?
yep
start with the first error in your console. you're getting a NRE in Start as well because you never assign activeObject
also your !IDE looks unconfigured
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.
i dont think it is.. Monobehaviour is Blue
ohh nvm it isnt
it supposed to be green
yeah it seems they are using a vs code theme
i only realized because Random, Vector3, and Time were all white in the last few lines
i wish it would return meta data with the screen grab 😉
letting all know its not config'd lol
booting up my navmesh example atm.. i'll ping again if i can find a solution
aye, so goal is for (my agent, atleast) to never move, cuz he cant get to me..
@grand gale
is there a navmesh placed on the other side too?
yea
using UnityEngine;
using UnityEngine.AI;
//SpawnCampGames.com
public class NavMeshDestination : MonoBehaviour
{
public NavMeshAgent agent;
public Transform playersTransform;
public void Update()
{
if(Input.GetKeyDown(KeyCode.Return))
{
// Check if the destination is reachable before setting it.
NavMeshPath path = new NavMeshPath();
if(agent.CalculatePath(playersTransform.position,path) && path.status == NavMeshPathStatus.PathComplete)
{
// The destination is reachable, set it as the agent's destination.
agent.SetDestination(playersTransform.position);
Debug.Log("Destination is valid and can be reached!");
}
else
{
// The destination is not reachable; do not move the agent.
Debug.LogWarning("Destination is not reachable!");
}
}
}
}
yup u can use it if u like
are the navmeshes separate
they're two different static planes
no i mean like
the first plane has the navmesh surface component right?
when you bake it, does it bake the second plane too?
yea
oh okay
oh it's not that, it does the same for me too, it was more like
"maybe yours arent the same navmesh"
and thats why it works for you and not for me
but seems thats not the case
okay well
that seems to work for some reason?
thank you
np, good luck
hey guys, im having trouble understanding how to pick a random enum, anyone got a min to help me'?
get list/array of enums, generate number from 0 to collection length, access collection using that generated number as index. it's that easy
this is the part im having a hard time understanding "access collection using that generated number as index"
i think im just confused on the syntax
enumArray[randomNumber]
have you never used an array before?
also you probably want to cast the array to the type of your desired enum
pretty limited but yeah
MyEnum[] enumArray = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToArray();
not exactly the prettiest line but since the generic GetValues method doesn't exist until .net 5 we have to cast to the correct type. substitute MyEnum in that code for the actual type of your enum
or i guess Array.ConvertAll may even be a bit better here instead of the Cast and ToArray call
and thats gonna give me an aaray of enums right
?
and i can pick my random number from there
it's going to give you an array of the values of that specific enum type, yes
something like this should also work
MyEnum is a variable i pass in from the function asking for the random enum
(no need for the last cast in the example)
why not use a generic method instead of passing the type?
ah yeah, forgot you could just explicitly cast the array like that, but i never like doing that
it needs to know which enumtype to return the random enum, bad naming on my part
use a generic method. if you pass the type it makes it significantly harder to return the correct enum type
something like this should work for generic (untested)
yep, exactly what i was typing up
that goes way beyond my comprehension tbh
i appricate you trying to help though
Basically the <T> is a wildcard "type", so it is substituted where ever you see T
how would you call that function?
you know you can just post the code directly in discord instead of screenshotting it every time, right?
yeah, i just like typing it in an ide 🤷♂️
liteshot makes it super easy to just screenshot it lol
just use win+shift+s
and drag a box where u want to screenshot
its on ur clip board and u just ctrl+v
ctrl+c, ctrl+v is easier
Enum.GetValues has a <T> hard typed version now, no more need to cast it :3
not in the version of .net unity uses 😉
Oh wait is that a dotnet and not C# one? My bad D=
it's .net 5
https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-7.0#system-enum-getvalues-1
unfold the .NET 8 and other versions accordion
but yeah the where T : Enum is basically just a constraint that <T> has to be derived from Enum, the constraints are useful since having them allows you to make assumptions for what functions are available to be used with the type, etc.
may i just essentially copy paste this without completely understanding?
OHHH
that makes alot more sense
like if you wanted to construct a new instance of a generic type type in a function, you'd need to do something like where T : new() which ensures that anything thats passed into it can be allocated to let you do something like new T()
error goes away now that we have the constraint
thats super neat the short variable names trip me up alot when trying to learn new thigs
yeah, some people make them more specific like in the case its restricted to an enum like the previous example, you might use <TEnum> for like "typeEnum", or whatever
you can also have multiple generic types available in the same function/class, like void Example<T1,T2>(T1 firstParam, T2 secondParam)
does anyone knows what this error is??
'SBaseStat' is missing the class attribute 'ExtensionOfNativeClass'!
i have tried deleting Library then reimporting all assets this error still persist 😢
[System.Serializable]
public struct SBaseStat
{
[SerializeField]
public float health;
[SerializeField]
public float speed;
[SerializeField]
public float attackPower;
[SerializeField]
public float armor;
}```
Presumably this used to be a component and added to an object, and now it's not so you must remove it from the GameObjects its on
If it was previously a ScriptableObject those need to be deleted
It generally happens when something has been a UnityEngine.Object type and added as an object, but isn't any more
Hey, i've asked about this before but I just ended up getting more lost and I'm honestly looking for clarity. I'm making a roguelike with an inventory system where every item does it's own (relatively) unique thing. one might give you health, another boosts your attack, another spawns gernades when you hit things, another gives you critical chance etc. etc. Is there a system I should use when doing something like this?
My current idea is one parent script with a child script for every item, but having that many scripts seems off to me, especially from an organization standpoint. Is there a better way?
I believe I mentioned this before, but some varient of Strategy pattern is very likely what you want
It really really depends on how much replication you have of common logic, and how well you can or cannot group these entities into common behaviors that can be Encapsulated
ScriptableObjects perhaps
they're quite versatile, so I suggest you watch a video on it and see if you can use it
Brackeys has a video on them
There's a specific type of pattern for these which is called meta magic, basically you seperate the controller logic from the effect
We would need more info on just how encapsulate...able... these things are to give a good recommendation
I was actually watching a scriptable object video and my main thought is that I can't really attach scripts or functions to every object (i think)
I really really strongly would suspect though that you likely can very much actually handle most of this logic with a small handful of scripts, with 1 "core" script to handle strategy selection, and a handful of basic strategies that have your logic encapsulated to specific "types" of effects
I remember you mentioning strategy pattern but looking it up I'm not really sure what you mean by this
You come up with encapsulated conceptual "behaviors" your "things" can have, and they are allowed to have more than 1 of them.
You then make a "strategy" for each of these types, and then a matching interface which provides the information for the respective strategy.
Then you just do a bunch of is a checks for if your thing has a given interface, and if so, pass its necessary data into the requesting strategy to consume that data and do the thing
To make it serializable with Unity, Id just apply the interfaces to your monobehavior on your prefab, and then you can just make a prefab for each type of inventory item
You alternatively can instead have all the fields, nullable, on a single prefab, and then a flagged enum that will enable/disable the respective fields from being shown/hidden in the inspector
I remember this now, I might be overestimating my project but I'm not really sure how well this would apply. My system will be similar to binding of issac, risk of rain, or gunfire reborn (specifically the scrolls). While effects can be similar most will do relatively unique things.
No I would say the vast majority of them can be broken down into "behaviors"
Binding of Isacc for example I can think of about... I would say maybe 5 or 6 distinct "strategies" for all the powerups?
Seriously? Not doubting you but just curious what your thought process is, can you list them out?
- Projectile
- Follow Along
- Stat modifier
- Trigger effect
Thats off the top of my head
Id prolly make a distinct strategy for each type of trigger tbh, like "OnHitStrategy", "OnKillStrategy", "OnDeathStrategy" etc etc
but any effect that simply just modifies your projectiles in Binding of Isaac can just be 1 single strategy, composed of like:
- How many
- What type of projectile
- Projectile Spread
- Projectile Speed
but those are just parameters
ok I actually understand what you mean now this would actually be pretty cool
So prolly what I would do is step 1,
- Make a MonoBehavior that holds aflagged enum for all the different types of strategies (and define that enum as well) (exposed to inspector), lets call this
Behavior, and the MB I would call something likeInventoryItem - All the serializable fields each strategy needs, grouped together, and then you can use
[ConditionalField(...)to hide/show them if the respective flag is set on the enum from #1 - An
IInventoryItemBehaviorinterface or whatever you wanna call it, that has a property getter for the enum value it belongs to, and functions for all the stuff inventory items can do, prolly as like an event or whatever? likeOnPickupOnInventoryOnEquipOnDropwhatever is needed - A concrete implementation for each
BehaviorofIInventoryItemBehavior - An
ItemBehaviorSelectorSO that has the list of all the ItemBehaviors you made in 4 (stored as aDictionary<BehaviorEnum, IInventoryItemBehavior>, and it takes in an inventory item and iterates over the behaviors and invokes them if the item has that behavior flagged
Your code should effectively end up looking like:
// Inside of your ItemBehaviorSelector
public void DoTheThing(InventoryItem item)
{
foreach (var flag in item.Flags.GetUniqueFlags())
{
Behaviors[flag].DoTheThing(item);
}
}
This method looks decent from stackoverflow to get the GetUniqueFlags method
https://stackoverflow.com/a/50481101/7839602
(I swore C# had a baked in way to do this now but I guess not yet)
I hate to bother you but I honestly still have some questions (there are some terms you're using that I'm not entirely familiar with)
A little confused about the neccesity of the flagged enum. Wouldn't this be the same as having every interface have its specific variables it needs for the actions?
yeah so, this example I am giving is for if you want 1 single monobehavior that just has all the fields you need.
Due to the way unity's serialization works, I think 1 single MB that just has all the fields, but nullable, would be way easier to maintain
the interface approach would be likely a little bit more performant, maybe, but it would be much more painful to maintain
Why would it be more painful? If I want to implement a new type of item I would just add a new interface and implement, rather than have to go back and change everything? Is there other reasons?
Also, What is a "SO" (An ItemBehaviorSelector SO that has)?
scriptiable object
my fault
So if you have 5 items that all implement the IFoo interface and it requires the params (fields) A, B, C, D set, you'll need to re-implement fields A/B/C/D on all 5 of those implementations
It 100% boils down to one simple thing:
Do you desire/need the support to have more than 1 behavior on a single item? I would typically just go with yes to be safe
cuz it would suck if you limited yourself to 1 per and then suddenly were like "Oh now I need more than 1 on some items aaahhhh"
Ok that actually makes a lot of sense
My code actually is very type anonymous. The only things I check for is targeting, but if I were to use an item, it's the item itself that has the logic for what it does and I just call its method.
nice part is you can nest em :3
I don't even know what you mean by this 😭
So lets call these things just plain ole Entities to make em very generic
Lets say you have ProjectileBehavior which expects a Projectile field to be set on the item... And you could make Projectile field type be... another item
And then you can put an Arrow item on the Projectile field.
And then you perhaps could put the Explodes behavior on Arrow make it an exploding arrow...
See how you can nest stuff :3
My ability controller here, basically all my triggers and stuff are lists which I don't really care for the exact type, only the interface implementation
I can actually merge all the triggers, but for editor simplicity I spread it out a bit
that's actually really really cool
This is basically what we are discussing, but one handy thing is just having a flagged enum at the top to enable/disable what gets shown cuz you may very quickly find that that list grows and grows and grows and gets unweildy
yeah flagged enum and bitwise operations are huge
And then you can only run the logic that matches what flags are set in that enum field is all
that way you arent doing a bajillion if checks for "is this set? is that set? are those set?"
you can break em down into "behaviors" to sort of "group" those sections up, and you may even have already noticed you are naturally "grouping" your behaviors up there :3
honestly, it's very hard to do these stuff purely of oop. It's possible but you'd spend more time planning than implementing.
Debug.Log(string.Format("\n----------\n1: {0} : {1}\n2: {2} : {3}", atm1.pressure, atm1.temperature, atm2.pressure, atm2.temperature)); Logging like this, the console shows it like this:
Why aren't I seeing anything except for the first line?
so it just lets you save a bunch of effort on having to do a bajillion "if" checks and instead just iterate over the behavior flags and invoke the matching "strategy" for em
What is a property getter? you talk about it in step 3?
checks are fine, I use flags mostly for modifiers mostly. Does fire damage and speed modifiers affect this ability?
The console only shows 2 lines by default. Select the log to see the whole thing
or change the settings
Ah, thank you
{ get; }
Basically your interface should have
Behavior Behavior { get; }
(Behavior being the enum we talked about)
If something turns into an ongoing conversation with explanations and followups, can a thread be made please?
Specifies all classes implementing that interface must have a public property called Behavior of type Behavior with a public getter exposed
Right cause the interface doesn't actually do anything it just provides a skeleton
ok ok makes sense makes sense
its more like a contract the class agrees to adhere to
as vert said if you got any further questions, make a thread for this and ping me on it :3
alright real i've got 1 (or 2) more lmao
which is better performance wise for moving an object continuously - using Update() or using coroutines?
starting a coroutine is slower, but if this is just a few objects you'll literally never notice any difference
if you have a ton of objects, you can have 1 script manage all X objects. rather than have 1 script per object
unless you're pumping out a bunch of coroutines it probably doesn't matter
i've a buff class and usually running 200+ coroutines an update, but I am looking into changing it all
The main difference would be ease of yielding statements
yeah it comes down to having the ability to fire and forget, but if it's a larger system I'd totally just bind it to an update loop
You could probably have some convoluted queue of delegates or flags and whatnot but it'll likely not be worth the hassle.
How do I disable a TextMeshProUGUI's renderer? I need to disable the renderer specifically. No modifying of color, font, size, or setting the game object or component to disabled.
why can you not just disable the component?
because it will trigger OnDisable and OnEnable
and what's wrong with that..?
I dont want to trigger those
why
why can't you change the color then
There are some logic in it that I don't want to trigger.
if you just disable the component then it will only trigger its own OnDisable
Yes exactly
it's renderer is literally the canvas
why cant you change the color
Not possible in this scenario
why not
why?
i will have to walk you through the entire system to explain
perhaps put it as a child of an object with a Canvas Group component
then change the alpha on that instead
that's not directly modifying the TextMeshProUGUI component
or give it a Canvas component and disable that
TMP_Text.renderMode looks promising
I can't check, but does it not use a Canvas renderer?
Why cant you just modify any of those others?
it does
Theres one other thing and thats modifying the camera mask potentially
Then enabling cull is the answer, no?
is that enableCulling
Does that require putting the text in its own canvas?
Oh it doesn't
Oh yeah that did the trick thanks
How in the world do I get shadows to follow the QualitySettings.shadows setting in URP? When researching it I see something about setting the lights to follow the quality setting, but i can't find that option anywhere. I see an actual option on the lights to set the shadows to off / hard / soft, but not following quality settings. Same for shadow cascade, although I think that may need to change that in the URP asset I'm using.
this is a code channel. perhaps you want #archived-lighting or #archived-urp
well I figured it has to do with code since I cannot find it anywhere on the actual asset settings, but I'll ask there too if I can't find a response here.
oh, also I am setting QualitySettings.shadows at runtime, so I figured maybe that's causing something to break and I need to do something extra?
Hey all! I have this slingshot model with armature I made and was wondering the best way to go about programming it to make it functional and "fling" things
https://media.discordapp.net/attachments/948011725012205569/1135789368477491271/osd1XI4NkM.gif
Hello, I am building a combo system for my game and I would like to know an efficient method on how to do this. Im trying for the efficiency of a Dictionary look up.
So with a dictionary you have a key and a value, say fire element gives water in the dictionary, or just a keyvaluepair for that matter.|
But how would I achieve say a lookup of (fire, water) and have it return (steam) for example or in the context of ints it looks up (1, 2) returns (17), but (1, 3) returns 10.
and if there is no value at say (1, 4) return (0).
my first reaction is to parent the baby to the slingshot part you are dragging around on trigger enter or something. i think if it has a rigidbody you can apply a velocity to it to 'fling' it and then unparent it
maybe you need key to be Fire and value to be a "Combo" object that contains a list of compatible combos, if "Water" is in *that * list, return steam, if ground is in that list, return ash or whatever. so your dictionary value is another dictionary essentially
should work, there's probably a more elegant solution though
I kinda did something like that but I didnt love it, I had the object itself contain its combos and if a combo element itself was used contain its components. it works, it for sure works but I feel there is a more elegant solution. Well I know it exists im just too inexperienced to know lol
Well the way I would do the math of firing something is find have two empty game objects and find the distance and the position of the sling relative to the "holder" or what ever its called and add a force vector.
Vector3 slingStuff = holderLocalPosition * Vector3.Distance(sling, holder) * power;
objectInSling.rigidbody.AddForce(slingStuff, ForceMode.Impulse);
if your "Element" is a class it could make sense to have the combos in there. you only need the dictionary in the Element class then, wasn't sure how your setup works but maybe this looks better? (forgot how to format code in discord..)
private void TryCombo(Element elem1, Element elem2) { Element newCombo; if (elem1.TryGetCombo(out newCombo)) { DoStuff(); } }
I was using scriptable objects for each element
not that it matters it would work about the same anyway
can you do keyvaluepairs as a key itself in another keyvalue pair
thats kinda cursed im not gonna lie
i probably would avoid that haha. "Fire, Water" would be different than "Water, Fire" too
hm your right
there's prolly a way around that though :p
oh wait normalize holderLocalPosition
you'd do (slingTarget - holderPos).normalized not just normalizing the position, or? 🤔
Really appreciate your help! This is the outcome which is close but I just need a little more assistance to get that true "slingshot" feel
This is the code
public void OnEndDrag(PointerEventData eventData)
{
Vector3 slingStuff = gameObject.transform.localPosition * Vector3.Distance(gameObject.transform.position, holder.transform.position) * power;
objectInSling.transform.parent = null;
babe.isKinematic = false;
babe.AddForce(slingStuff, ForceMode.Acceleration);
}
}```
Sorry about the crappy gif quality as well my screen recorder just busted itself lmao
well this all depends on where the actual empty gameobjects are and if the holder is where the holder actually is
one sec
why is the amount of force being added using the localPosition as the direction of force?
when i said the local position i ment the position of the holder relative to the sling shot top
thats my bad
holder.transform.InverseTransformPoint(slingshot)
.normalized again
thats right right? its 2 am and im not sure if im thinking straight
that should give a direction
there are other ways to do it its just the first that came to mind
position shouldn't be multiplied into added force
direction is just (endPosition - startPosition).normalized
i don't see why you would want to make the code look even more confusing by using inversetransformpoint (which being normalized still wouldn't be the correct direction)
yeah thats how you do it
would it really not?
well it depends really on which object is which, i don't actually know that. but i would assume it is likely the direction would be backwards
well if its the position of the slingshot relative to the handle it should be the right direction
it's also just a wasteful call when subtraction is much quicker and doesn't need to call into native code
yeah
So to conclude,
or the other way around I honestly cant be bothered to think about that lol
don't bother normalizing then multiplying by distance
good?
endPosition - startPosition is already the direction and distance. normalizing just removes the distance
remove the Vector3.Distance call entirely
ohhh
i never thought of it like that
i meen yeah it makes sense, should of payed more attention in geometry or whatever
trig?
I like how this isnt even my problem and we are talking back and forth about it
Like brother could have written it down minutes ago
I'll give that a try!! Thank you all so much!
I have an issue with colors in non UI TextMeshPro Text (both have same color in inspector, left is non ui, right is ui tmp showing correct color) any idea?
Hey I had been wondering something
My Case:- I have alot of child objects with the same script attached to each of them. Now only one of the objects can be enabled at a time.
My doubt:- I would like to call a function of the script on button press. Now there would be almost 10 objects with the script attached. So what's more efficient, having no checks and update and just calling the function for every instance of the script on button press even though only one of em would be active, or a simple check for the button under update working in the only script active?
Thanks
if they're inactive, the Update won't run
What I would do is to check for button press in another script and trigger an event, instead of enabling/disabling the script you just have to subscribe/unsubscribe to this event
yeah could do this, and just subscribe/unsubscribe in the script's OnEnable/OnDisable
Yeah sure that's intended
No actually I am not enabling disabling the scripts. I am enabling disabling the gameobjects containing the script. Lemme show you my setup in a sec
I have seperate holders for different weapons which I enable/disable according to what the player has equipped
All of that is well networked but let it be
Each weapon holder has this script
It's still wip. Each weapon would have it's own configuration and animations in the inspector
if you disable the gameobject, the script is disabled so no update, so no input detection (if using InputManager)
Yep
(btw WIN + SHIFT + S to take a partial screenshot 🙂 )
So my question is would it be more efficient to include a check in the script itself and play anims if the button is pressed or should I stack all the scripts here instead to prevent unnecessary checks.
please send screenshots
I am sorry man, I just don't use discord on pc
You can use it on web even
So what I am confused about is would there be an unnecessary overhead if the button tries to call the function for every weapon available even if only one of them is supposed to be enabled at a time? Should I use a check under fixedupdate instead?
If the objects are disabled, it's not like update or fixed update is gonna run anyways
And you dont want to throw things in fixed update just for the purpose of running things less often
Yeah I get it
There would be just one instance of the script functioning at a time. My question is would Unity still try to call the function for every instance stacked there no matter if they're enabled or disabled?
Lets say I wanna call this on button press
I'll add all the instances of the script there
Only the one enabled would have its function called when the button will be pressed
But what about the ones which are disabled? Would unity exclude them? Would unity still try to call all the functions at once even if only one of the scripts in enabled
Would that be an unnecessary overhead in comparison with a simple check every frame in the script instead
The only thing that happens is unity stops calling it's own functions, update, fixedupdate, etc (with some exception for trigger functions)
It doesnt care about what you do with your functions, meaning you can still call your own code
Keep in mind I'll have 10+ weapons with the same script
Anyone able to look over my clamping code it still let's me make the Z position whatever when I drag
public void OnDrag(PointerEventData eventData)
{
Ray R = m_cam.ScreenPointToRay(Input.mousePosition); // Get the ray from mouse position
Vector3 PO = transform.position; // Take current position of this draggable object as Plane's Origin
Vector3 PN = -m_cam.transform.forward; // Take current negative camera's forward as Plane's Normal
float t = Vector3.Dot(PO - R.origin, PN) / Vector3.Dot(R.direction, PN); // plane vs. line intersection in algebric form. It find t as distance from the camera of the new point in the ray's direction.
Vector3 P = R.origin + R.direction * t; // Find the new point.
P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
if (P.z <= -0.1f || P.z > -0.019f)
{
transform.position = P;
}
} ```
Log the z value before and after change
If the after value is correct, elsewhere has got the value changing.
Wait what do you mean sorry
I'm not sure how and where to declare it
Would I just ran this at the start as well??
P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
if (P.z <= -0.1f && P.z > -0.019f)
{
transform.position = P;
}```
Turns out I'm an idiot and was using && instead of || but now as soon as my mouse exits the bounds it stops moving entirely
public void OnDrag(PointerEventData eventData)
{
Ray R = m_cam.ScreenPointToRay(Input.mousePosition);
Vector3 PO = transform.position;
Vector3 PN = -m_cam.transform.forward;
float t = Vector3.Dot(PO - R.origin, PN) / Vector3.Dot(R.direction, PN);
Vector3 P = R.origin + R.direction * t;
P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
if (P.z <= -0.1f || P.z > -0.019f)
{
transform.position = P;
}
}
will be happy to look at it if the variable are named for humans
apart from the edge case your if statement makes no sense
I'm trying to use OpenFracture on my custom mesh, but nothing happens. Any idea where to begin debugging?
okay this is annoying af, Im like 99% sure i set a variable to right value, and it shows in both debugs and in Visual studio debug window at right value, but then when i use that variable couple frames later in different method, its reseted
post relevant scripts
like only explinations i can think are:
-it doesnt save it for some reason
-it saves it at wrong object/i have some clone object fake shenanigans going on
-idk, other wierd bs
codes are rly complex full of stuff(that isnt very well commented,) but i can try to gather something
idk is this anything i can get help with because its so messed up:D
ah so interfaces are very similar to abstract classes
pros: you can implement multiple on one object
cons: You can only have methods and not vars it looks like
you can do properties tho
yeah
The interface itself will not implement something
yeah
This is what I was saying
yeah, i misspoke ig
Hi everyone, just a quick question but is it possible / easy (as this is only a minor thing) to render handles on top of gizmos? Right now I have a handle label, and its rendering behind some Gizmos.DrawLines just wondering if I can reverse the order?
figured it out, My other code referenced a prefab, other referenced instation of it, but code was so messy i couldnt figure it out(and i doubt anyone here would have), but thx for offering a help
i hate programming sometimes
i spent like 4 hours of procastination on that bug
if your code become unreadable / unmanageable it is time to maybe refactor things
yeah propably :D
i have a string like this "10010" and i do this to it:
List<int> bar = level.levelData[progress]
.Split()
.Select(str => int.Parse(str))
.ToList();```and for some reason, it returns with a size 1, as the same 10010 but this time as an int
how do i get it to split correctly into individual chars
get rid of the .Split()
but i want my result to be [1, 0, 0, 1, 0]
You should not do Split here because it will enumerate the individual characters then
thats exactly the point
Otherwise it will enumerate the single array entry Split returns
It's not splitting your string
Your split is literally just giving you back the same string as one entry in an array
So what PraetorBlue said, remove Split
Just remove Split and it will work
string implements IEnumerable<char>
A string is an array of characters
So Select will enumerate the characters
(it's not actually an array of characters but it will be converted to one by c#)
does int.Parse not take chars?
Ok this is a bit dumb because it indeed doesn't
Here's proof: https://dotnetfiddle.net/2FhXtc
Test your C# code online with .NET Fiddle code editor.
just do .ToString()
You can probably get rid of the ToString stuff someway but this works
Top one is the current one, bottom is the suggested fix
[Fork] Unity Template [Postma] | Test your C# code online with .NET Fiddle code editor.
Thanks for creating the exact same fiddle lol
oh lol
flittle my dittle
didn't even see
Anyway, ToArray and ToCharArray basically does the splitting you want
becauase I was too busy working on my fiddle lmao
its just weird that it does it for you
seems like something i'd rather have control of
the ToArray isn't needed though
it's not weird if you understand how Linq works
you're using Linq (Select is from Linq)
Linq works on IEnumerables
string is IEnumerable<char>
so when you call Select on a string, it operates on each char
im used to java lambda functions
works the same way
yeah but i think you have to specify split in java
I want to make a point but that class is so goddamn big
Individual characters are fetched internally
if you do java String s = "123109"; s.Map(c -> Integer.parse(c)); it will work on each character in Java
hm interesting
So there's no "array of characters" here. It's a string that will have its characters in memory fetched when you want an array of characters
alright so the data splitting works now
OK that was not quite right it's been years since I did Java
Stream<Character> characterStream = testString.chars()
.mapToObj(c -> (char) c);```
yeah the chars()
that just gets the character array though
because Java doesn't have the fancy IEnumerable interface shenanigans
does the same thing as a split and has to be explicitly stated
it's not a "Split" call
minus the to string
no, split breaks a string into multiple substrings
chars gives you just an array of chars which is the whole string
but your confusion was that:
"1001".Split() actually gives you ["1001"] not ['1', '0', '0', '1']
The reason why you got a while string out is that .Split() operates on whitespace if you don't specify the delimiter, but your string had none
i really only use split when im doing code competitions
ig i got it confused with python
Is IDragHandler deprecated or something? Can't find it in the newer scripting references
it's not
Could you give me a link to it?
it's in the package docs now
for UI package
@orchid bane if you just type IDragHandler it should give you the suggestion in VS no ?
It does but I wanted online docs
void Update()
{
timer += Time.deltaTime;
// Spawn one note per BPM if you haven't run out of bars.
if (timer >= ((level.bpm / 60) / 60) && progress < level.levelData.Count)
{
// Bars are saved in json as 6 char long strings.
List<int> bar = level.levelData[progress]
.Select(c => int.Parse(c.ToString()))
.ToList();
// Spawn a note at a spawner if pos within bar == 1.
for (int i = 0; i < bar.Count; i++)
{
if (bar[i] == 1) Spawn(spawners[i]);
}
timer = 0f;
progress++;
}
// To restart the level.
if (keyboard.spaceKey.isPressed) progress = 0;
}```whenever i run it for the first time, it's able to spawn the notes with the correct bpm spacing apart, but whenever i restart the progress, every bar in the config gets instantly spawned.
for (int i = 0; i < bar.Count; i++)
{
if (bar[i] == 1) Spawn(spawners[i]);
}```
well you're just looping over them all and spawning
a bar is just one row of notes
no time delays in here
but it's spawning all the bars at once
right
Hey guys, how to await a task in a coroutine, while also getting the value
just use async if you wanna use Task
whats point of Coroutine then
the time delay is within level.levelData[progress]
yield return new WaitUntil(() => myTask.IsCompleted);
you're not in a coroutine, and there's no yield, so there is no time delay
everything will happen instantly
?
this is the config for reference
every frame, it's only supposed to get the bar from whatever progress is
Thanks!
180 / 60 / 60 = 0
0.05
@jade phoenix since you never reset the timer, when you reset the progress it probably spawns all the notes at once?
i do reset the timer
yeah i thought about it and it doesnt make much of a difference
the condition still works
It would delay all the notes by one though
have you tried setting timer to 0 along with progress?
would you know why the bubbles spawn so closely together?
i set the bpm all the way down to 4 and it still seems like they're spawning in pairs
We here handle subs and unsubs to event in OnEnable and OnDisable, but how do they handle them in other dev fields?
your math is wrong. its supposed to be 60f / bpm
would i just multiply that result by 60 to represent it in seconds and not minutes though
1 minute = 60 seconds
60 seconds / 180 beats per minute = 0.33sec between each beat
You would perhaps subscrube within constructors and unsubscribe within destructors
e/subscrube/subscribe
AFAIK there are no destructors and deconstructors are only for tuple usage
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers
I guess it's called finalizers
They are called by GC but AFAIK you're not collected as long as you're subscribed
True that, you'd have to implement IDisposable to dispose of the object. The basic answer to your question is that objects have a lifetime, and you'd sub/unsub at the start/end of it.
public void OnTouchPressed(InputAction.CallbackContext context)
if (context.performed)
{
var touchPos = Touchscreen.current.position.ReadValue();
Ray touchRay = Camera.main.ScreenPointToRay(touchPos);
RaycastHit touchRayHit;
if (Physics.Raycast(touchRay, out touchRayHit) && (touchRayHit.transform.CompareTag("Bubble") || touchRayHit.transform.CompareTag("Bad Bubble")))
{
if (touchRayHit.transform.parent.parent.GetSiblingIndex() == currentRunwayInd && Physics.Raycast(touchRayHit.point, -touchRayHit.transform.up, clickSpaceLayer))
{
Destroy(touchRayHit.transform.gameObject);
Debug.Log(betterTimer);
}
}
}
}```how can i change this so it can detect whenever multiple fingers tap down in different places at the same time?
iirc there is an Input.touches list~~, gotta doublecheck~~ there was! you can probably use that 🙂
TMProUGUI.GetRenderedValues is giving me outrageous values
This is the hierarchy. I'm trying to get the size of "lesson" in order to resize "LessonModule (Clone)"
The only thing I changed from the default implementation of Scroll View from Unity is that I added both a Vertical Layout Group and a Content Size Filter to the "Content" gameobject
are you trying to reference the transform lesson?
what's the goal here?
To be able to add modules procedurally so it looks like this
Isn't this just a VerticalLayoutGroup
why do you need to call weird functions and get heights
Lesson is a TextMeshProUGUI and i need to know how much space the text inside it occupies
Because vertical layout group only allowes for fixed sizes
not true at all
By sounds of it Rocco wants to scale the nodes depending on the text?
you need to read this:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIAutoLayout.html
Yup
You'd still use a verticle layout group on top of it though
VerticalLayoutGrou[p and layout elements and content size fitters solve all of this automatically
you don't need any code
But it doesnt accound for the size of the text of one of its childs
yes it does
if you set it up properly
I'll take Praetors word on this, I've not had a need to automate with text
Te text is a child of the child of the vertical layout group
indeed it is
you need to read that thread
So I need to make the text the parent object?
There is tecnically two texts, one for the title and the other for the text, idk how to go around that
I'll read the other thing you sent, see if there is a better solution
I am working on a mechanic that allows me to paint walls / objects and etc... I already have the code down for grabbing the correct submesh to get the material where the raycast hits but I need to figure a way to handle allowing the player to pick new materials to paint.
I was thinking of having a struct for each texture which would contains
- Texture
- Array of "Tags" strings?
Maybe contains all of these into a list? and have their index as an ID that I save on the object? So for instance I might have
wallData.paint[1] = 3;
When I select the object I could get the tags on it for compatibility and then use a filter on the list of textures? But I duno if this is messy
How to make completely dark areas inside objects in an isometric game. Scripts? Shaders?
Maybe have a flat black layer and use a mask on top of rooms?
The second method that I'm considering using is to check the vertex height in the shader. If it's above the wall height, then make the surface dark.
I don't know how i did it, but now GetRenderedValues() is giving me the appropiated results...
Valid option. It depends how your models are because I just assumed they were rooms placed with gaps between but if you have an actual surface there, that could work
*part of the surface
the rest is camera background
raycasts and colliders at the most basic level.
Note that the collider you interact with for your interaction system does NOT need to be the same as the physical collider the object might use in the game world
As I already said:
Note that the collider you interact with for your interaction system does NOT need to be the same as the physical collider the object might use in the game world
You can use a much larger/simpler shaped collider for this purpose
Also
You must need to interact with the origin of the collider
I have no idea what this means
void Update()
{
map.ForEach(c => {
float h, s, b;
Color.RGBToHSV(c.Value, out h, out s, out b);
h += progress;
progress++;
if (progress >= 255) progress = 0;
c.Key.GetComponent<Renderer>().material.color = Color.HSVToRGB(h, s, b);
//c.Key.GetComponent<Renderer>().material.color = new Color(Random.Range(0, 255), Random.Range(0, 255), Random.Range(0, 255));
});
}```would anyone know why changing the hue of a material's color makes it completely black?
Color values are from 0 to 1, not 0 to 255
I think 255 is Color32?
divide to 255?
Hue is also from 0 to 1
but isnt hue one of those things that just wraps around if you go over
like an angle
or am i just crazy
Could be, but the hue values of the HSVToRGB method are from 0 to 1
I mean it's from color and none of the colours inherently get the remainder so I'm not sure if hue would act any different
h += progress;
h %= 1; // wrap around if > 1```
ah fancy
unclear what progress is though
not if its a float
progress++;```
It's unclear to me why progress would or should change here
Even if it's a float, ++ will always add 1 no?
yes but that's not what the suggestion was
I assume progress starts at 0 and thus adds 1 and ends up 1 and remains one
float f = H * 6f;
int num3 = (int) Mathf.Floor(f);
float num4 = f - (float) num3;
From the IL code it looks like it's always going to be 0 @jade phoenix
OHH its cause i intially thought i was going to set the hue instead of increment it
@leaden ice They stated they want some rainbow effect but how does adding 1 to a 0-1 value ever change anything when you wrap?
I mean maybe they want:
h += Time.deltaTime * speed;
h %= 1;```
It still makes no sense to add 1 to a 0-1 value
indeed, hence the removal of that line in all my code examples
Are you sure you don't want a gradient, like so: https://docs.unity3d.com/ScriptReference/Gradient.html Then you can evaluate its value from 0 to 1
this cylces one time and then stops
why would it stop?
I think they just want to flip it once like making 0.2 = 0.8 and 0.5 = 0.5?
I duno why though
wat?
so like .2 + 1 wrapped is .8 or whatever
I'm using the example they provided here
show your code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you're never modifying the color in the map
I honestly don't understnd why you're even using a Dictionary here
but their code isn't using it
it's not syncing the color in the dict to the gameobject at all
Yeh I can see
I think they are thinking the value is a reference to the objects colour
Just do:
List<Renderer> renderers = new();
void Start() {
foreach (Transform child in transform) {
Renderer r = child.GetComponent<Renderer>();
renderers.Add(r);
}
}
void Update() {
foreach (Renderer r in renderers) {
Color c = r.material.color;
float h, s, b;
Color.RGBToHSV(c, out h, out s, out b);
h += Time.deltaTime * 10f;
h %= 1;
r.material.color = Color.HSVToRGB(h, s, b);
}
}```
@jade phoenix
your code is overcomplicating it
Also try to avoid getting the same component over and over, it's not all that cheap to do
GetComponent isn't cheap?
Nope. Cache the result of it.
it's relatively cheap but anything gets expensive after doing it over and over again
besides isn't it just ugly to have to write it that many times??
how do I set all lights to hard/soft shadows at once? I thought QualitySettings.shadows would do it but no.
I thought maybe I could use this, but it seems actually most of these properties are read only
you can assign an override asset with different settings:
https://docs.unity3d.com/2023.2/Documentation/ScriptReference/QualitySettings-renderPipeline.html
so I can only switch them, i cannot edit the values at runtime?
for readonly properties, it would seem so
why are soft/hard shadows not changable? that is so weird to me. How do other games provide graphics settings to their users if half of them seem to be locked?
I don't think this is a setting about whether to use hard/soft shadows
this is more about whether the pipeline itself supports soft shadows
I think hard/soft shadows are something that is configured on a per material basis
There's QualitySettings.shadows but that doesn't work in URP.
or a per light basis
hrm
well anyway, for QualitySettings.renderPipeline do I need to have a different pipeline asset, or can I load one from Resources and just edit the write values and set the override?
Is it ok if I ask a python question here real quick?
Have not used it in a year and every other coding server I’m in is dead
no because this is a Unity c# programming channel
try The Coding Den
last message on python channel is 1:50 pm you should be fine
Trying to modify and 'improve' a dungeon generating algorithm to fit my needs.
The algorithm as it currently stands works like this:
-
Place a starting room and add it's exits to a list (pendingExits)
-
For a certain amount of iterations, go through every pending exit and place a new room at them.
-
If the new room doesn't overlap anything, add the new room's exits to the pending exits list (skipping if it finds no room that doesn't overlap anything when placed)
The changes I want to make are:
-
Allow a way I can force there to be only a certain amount of a specific type of room placed(so I can define 'special' rooms which only appear once or twice throughout the generated dungeon)
-
Remove the iteration based generation and replace it with something that guarantees the amount of rooms generated
How can I modify the algorithm as it currently is to achieve this?
How can I modify the algorithm to include the changes I waant?
Is there a way to call a founction next frame?
use a coroutine
Is a coroutine always called next frame ?
no
a coroutine will let you write code like:
- wait one frame
- do something
It seems like " yield return 0; " makes you wait one frame. Thank you !
sure
or just
yield return null;
note that this only works inside a coroutine
Thank you!
speaking of, has unity added any kind of Task overloads to wait for 1 frame?
like, await Task.FrameDelay(int frames) or whatever
I saw this if you want to wait for a certain amount of frames :
public static class WaitFor
{
public static IEnumerator Frames(int frameCount)
{
while (frameCount > 0)
{
frameCount--;
yield return null;
}
}
}
public IEnumerator CoroutineAction()
{
// do some actions here
yield return StartCoroutine(WaitFor.Frames(5)); // wait for 5 frames
// do some actions after 5 frames
}
yield return null; is better. I believe that if you do yield return 0 then it will work, but the 0 will be boxed, causing a GC allocation.
does anyone know any good resources for mobile haptics? cant really find anything online
Task.Delay() does that and doesn't allocate anything extra afaik
err
Task.Yield()
don't use delay!
do you have a way to convert a 'pending exit' into a dead end?
if so, your second constraint is quite easy to meet - instead of placing a room for every pendingExit on each iteration, just pick one of them at random. repeat until you've placed numRoomsDesired rooms, then convert all remaining pending exits into dead ends.
If you have to do it by placing extra rooms on each pending exit (i.e. placing an extra room which has no other exits) then you repeat until you've played numRoomsDesired - pendingExits.Count rooms, then place the dead-end room at each pending exit. (In theory you might end up with fewer than numRoomsDesired this way because two pending exits might open onto the same tile).
Thank you!
would anyone know why it's not taking the method like its supposed to
it only works when i pass the method as a string
IEnumerator
yep . . .
?
Is this code inefficient?
Resharper unity plugin marks it as is, but everywhere I look online i says that transform is cached
it's fine
that's a microoptimization
what am i doing wrong here?
I think you get this if you are referring to a prefab
or a deactivated particle system