#archived-code-general
1 messages · Page 428 of 1
I have no idea what to assign it to though
ya loooking through here not seeing anything obvious lol..
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/api/Unity.Cinemachine.CinemachinePositionComposer.html
ah
its a struct
structception
var composerSettings = new ScreenComposerSettings(); composerSettings.HardLimits = new () etc. CinemachinePositionComposer().Composition = composerSettings
sometimes...I feel like it's easier to make a custom camera system than relying on cinemachine
but I'll try this
haha would probably organize it the same
much better than everything being a public field lol
I don't feel like I would need to make it so complicated
keep in mind this camera system has to basically satisfy hundreds if not thousands of different usecases
fair enough
in GraphView api, i want to save my custom nodes that inherit Node. Isnt there any other way, but to check the type of each element in GraphView.nodes?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm trying to access the trackedImage prefab to control it via a joystick
I couldn't find much info about it in the forums
can anybody help me with this pls
How have you confirmed that your states may be the issue? Have you used any debug statements or breakpoints to confrim the order of your logic?
I've fixed and reworked it
It was indeed the States system
The ordering of prioritisation was the issue
RenderTextures and Portals
State machines are HARD. I had to seperate the states into two enums cos they just didn't overlap properly:
Movement State has Walk, Sprint and Slide
Posture State has Stand, Crouch and Air
I don't even know if State Machines are the way to go for this Titanfall inspired FPS multiplayer
State machines are used often in games, though using enums to manage states is an option when you have just a few very specific states, but as your states get more complex or you have a lot of them, enums can be a bit hard to manage, personally I like using classes for states but you can also use interfaces - for example, you could have a "MovementState" class, that handles walk, sprint and slide - you cuold setup a FSM (Finite State Machine) that handles transitioning from "MovementState" to something else like a "SwimmingState" that maybe also handles diving - and when things get even more complex such as states deciding when another state can transition, maybe a BT (Behavior Tree) is more flexible, but yeah AI of any kind can be difficult for sure
Just wanted to know your feedback on the current movement systems?- https://astralli0n.itch.io/limitless
Do you think all the states work correctly?
The only thing I wasn't sure about at all was the Slide. I just made it so you have reduced friction and maintain the velocity of sprint and height of crouch
I genuinely don't know what I need to add for slide to work
if i were to make a function in a script (for changing rigidbody and transform properties) and call that script from somewhere else (a separate script for more advanced mechanics), will the object with script 2 get affected by script 1?
or will script one have to be on the object as well
The script does whatever you make it do
so i just need to pass in something like "this.[component goes here]" and it should work only for that specific gameObject?
If you do this.transform (or just transform) then it refers to the object that has the script. There isn't a similar shortcut to the rigidbody so it depends on how you access it
oh
well thanks anyway :>
Any help with this?
I've been trying to write a compute shader for a flip simulation. This requires a step to interpolate the velocities of a bunch of particles onto a grid, but i am not sure on how i should do this as something like interlocked add cant be used on floats
Hello so i fnally had my inventory done etc, but i gotta do a if check from an outside file, been on this for 3 hours cant really figure it out, all i need is just for this loop to finish, i allready know it can get the item v value
All it needs to do is say yes to my other file where my if statement is, and cancel the loop
Is this ranting or is there an actual question/concern?
I have been at this for 3 hours, i cant figure out how to stop the loop
break would stop a loop
As in, you found your item, so exit the loop?
Yeah ive debugged it alot with all messages, the value if i dont have the item then it returns fine to the other file, but if i do have the item... unity just freezes, since iam not closing this, save isnt working etc, its out of array
i mean, the other files use more id checks, but theres no need
Nothing here should run forever. When you say "other file", do you mean some other class or monobehaviour?
Yeah its for my smithing script
Normally, you'd have a local bool assigned false and set it to true after finding your element - to later return from the function.
so i need to get the item, and if (!player.inventory.HasItem(new Item(sword))) yeah its called sword w/e
using that to get the id, and that works, it returns back, but once i do have the item unity dies
Yeah i gotta close this part
Might be a good place to use Container.Contains() or something.
Been at this for like 3 hours, i tried everything i know lmao iam despirate
public bool HasItem(Item _item) => Container.Items.Contains(_item);
I don't think this piece of code is producing your infinite loop. It likely is attributing to it though as you've not fully implemented a false case.
Yeah, the loop is happening somewhere else.
So using the container... like the if (!player.inventory.HasItem(new Item(sword))) best i could get up with for now, its kinda wierd, but i had that safely returned
my savegave is having issues with it
deserialize or so
bool found = false;
//loop
return found;```
Inventory newContainer = (Inventory)formatter.Deserialize(stream);
Where in the loop you'd assign it true if found.
Can you show us what is calling if, and what is in the constructor for Item(sword)?
Never i really just used if and then else
Iam not really good so i make alot of messy code and mostly get away with it
Not this time, apparently.
I'm assuming you're either looping this has-item call because it isn't doing what you're wanting or the system somehow crashes later on because you've not got an implementation for false and later are expecting it.
Mostly i just returned to debug, and just stop everything, but once it does find the item it breaks, and i know its over that get part, since aslong as that is in then my save also breaks, ill put it on sql tomorrow in hope to avoid those further anoying warnings
We'll never know unless we see what you're seeing, so you are aware.
There isn't anything here that would cause the application to hang
if (!player.inventory.HasItem(new Item(sword)))
Debug.Log("");
{
else
}
Debug.Log("");
}
Thats pretty much what ive been using
Yeah ill keep u posted, i pasted these parts in paint to remember and for sure will work on it
That isn't relevant or enough information to resolve your problem
Right, since these debug logs come back, unless it finds the item
when it does find the item, it just breaks unity
@solar hawk If you don't know where the problem is, you're going to have to show stuff that you think is working well.
Start with the stuff that references what you think is wrong.
Your current implementation will always return true regardless of it exists or not
So literally, what calls HasItem? Search your whole project in VS if you don't know, because there is ZERO anything that will crash unity in that picture.
Oh xD
Really? guess u see my issue? XD
why not just return true inside the if statement and return false at the end? no need to go through the entire loop if you've found the object
That would also work.
There is an infinite loop in their project, and we are trying to convince them that this is irrelevant to figuring out what is causing that.
Let me try 😄
in that case they just need to attach the debugger and break all when the infinite loop happens and just look at what the main thread is doing
We'd settle for a look at whatever method references HasItem().
They haven't posted enough !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.mod.gg/imnmmrjpntnp/0
https://streamable.com/fvugxc
can anyone help me with my car controller 😭
A tool for sharing your source code with the world!
why is it tweaking
sure, but using the debugger can show exactly what is causing the loop. i'm not saying to place a breakpoint in this method, i'm saying they need to just break all (the pause button in the debugger) when the infinite loop causes the inevitable freeze. then just looking at what the main thread is doing will point to what the infinite loop actually is
You need to read about how to post code properly #archived-code-general message
Ohyeah my bad! i have no logs actually
That might be slightly advanced given the nature of the conversation so far.
Bump, also lmk if any more information is needed
#archived-shaders probably better section
Thanks
There is lots of jittering when I rotate my Camera, even though I am using Lerping to smooth it out? https://scriptbin.xyz/iyujuregan.cs
Can someone help please
Use Scriptbin to share your code with others quickly and easily.
It's a bit of a bad video but hopefully you get the point
Because you’re using transform rotation to rotate a rigid body
So instead of rotating the player itself, have a separate transform that the camera rotates on the Y axis, then get that transform’s direction to move your player in the proper direction
I know a real answer is probably "it depends" and "profile it" but could i get a general vibe check on how costly casting types is roughly? Just tinkering around with ways i'd prefer to handle some instanced content registration stuff and I'm curious what the kinda scale of it's cost is like. This wouldn't be in the context of something as frequent as Update() or anything but i just don't know if its a "avoid as much as possible" or more like getcomponent where its "not actually too bad just cache when you can"
Hey im trying to build a 2.5D Game in Unity with Hextiles.
I want my unit to move the most "direct path" (shortest by "direct line"?) if all of the tiles on it are similiar as the tiles on longer (per "airlines", not tile length)
(I hope this question makes sense, im unsure how to explain it)
https://paste.mod.gg/imnmmrjpntnp/0
https://streamable.com/41mmp9 hey can anyone help with my
A tool for sharing your source code with the world!
car problem
the car is doing some weird stuff when i move it
I assume this is the acceleration/deceleration forces causing this?
You should debug them
Also, what components does its children have
And where is the AccelerationPoint positioned?
hey i found the reason that it wasn't workin
i forgot to freeze the x and z axis
i have a new problem now
how do you script the chinemachine cameras
CinemachineCamera
just reference the component and do whatever you need with it
how would i be able to
change the
cinemachine follow offset
Well reference whatever component has that value and then change it
i don't know hwo to do it thats why im asking bor
lol
public AnyComponent comp;
void Function(){
comp.anyValue = 123;
}
Dont remember which Cinemachine component exactly has the offset value
Also I apologize for my past vague responses
not a problem
thanks for the help
So I'm running into alittle bit of a problem, with my mouse movements.
I'm trying to move the SelectedItem slots with my mouse wheel but for some reason, the game acknowledges that it's meant to move but doesn't actually move. I must also say that everything works with the hotkeys it's just the mouse wheel.
The mouse code is in ItemSlot.cs.
Code:
https://paste.mod.gg/wnixbnskbxje/0
These are the 2 deubg statment's I get:
Scrolling to slot 0
UnityEngine.Debug:Log (object)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:162)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
Selected slot 0: ItemSlot_2
UnityEngine.Debug:Log (object)
ItemSlot:SelectSlot (int) (at Assets/ItemSlot.cs:134)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:163)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
A tool for sharing your source code with the world!
Alright, here are two lines of code, both print functions.
The first one prints a string containing two references to two variables in the same class.
The second prints the same string, but contained into a scriptable object.
In the editor console, the first string gets printed correctly, it shows the item that has been collected and the quantity, the second does not, the variables in the string don't get interpreted, why?
string interpolation only occurs on $"" strings, as a syntax thing
also, uh, smart object? you sure you don't mean scriptable object?
whoops, yeah, scriptable object
lol
so, this doesn't work either...
yeah i wouldn't expect it to
that entire string is put into a normal string
$"" would need to exist as a string literal in code
you can't do that from the inspector
i see, i was trying to make an announcement system and thought it was a good idea to store each line in a separate file rather than in the code
generally for stuff like this you'd need to define what values are available to be formatted in, not sure how you would do that in unity
idiomatically, at least
You can use string.Format() but that needs you to provide the placeholders with numbers and you provide the strings as other args. e.g:
string.Format("Thingy: {0}", "foobar");
Addressable profile path strings actually have this functionality though for using static variables at runtime
thanks, i'll look into that
can anyone please tell me why the OnTriggerEnter part of this code won't work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CookingScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string Ingredient1 = "None";
string Ingredient2 = "None";
string Ingredient3 = "None";
List<string> stringList = new List<string>() {Ingredient1, Ingredient2, Ingredient3};
}
// Update is called once per frame
void Update()
{
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Apple"))
{
Debug.Log("Apple");
}
}
}
}
its inside the Update function, move it out to be inside the class instead. also format ur code better next time
how do i fix this
Fix what
Look at it in scene view with the collider gizmos
how do i make peeking around walls like in call of duty
rotate your camera side to side on a pivot when Q or E is pressed
no
its supposed to lock on edge of wall
when u aim near it
then do what I said but make it snap to a wall
raycast to see if there's a wall in front of the player
private void ChasePlayer()
{
float distanceToPlayer = Vector3.Distance(transform.position, playerPos.position);
if (distanceToPlayer > 9f)
{
agent.SetDestination(playerPos.position);
if (!animator.GetBool("CloseToPlayer") && !isAttacking)
{
transform.LookAt(playerPos.position);
}
if (agent.velocity.magnitude > 0.1f)
{
animator.SetBool("IsChasing", true);
}
agent.isStopped = false;
animator.SetBool("CloseToPlayer", false);
}
else
{
agent.isStopped = true;
agent.velocity = Vector3.zero;
if (!isAttacking)
{
isAttacking = true;
StartCoroutine(AttackPlayer());
StartCoroutine(AttackDelay());
}
}
}
private IEnumerator AttackDelay()
{
yield return new WaitForSeconds(1.6f);
if (playerManager.playerIsDead)
ResetEnemyMovment();
agent.isStopped = false;
isAttacking = false;
SmoothLookAtPlayer();
}
private IEnumerator AttackPlayer()
{
animator.SetBool("CloseToPlayer", true);
yield return new WaitForSeconds(0.8f);
float distanceToPlayer = Vector3.Distance(transform.position, playerPos.position);
Vector3 directionToPlayer = playerPos.position - transform.position;
float dotProduct = Vector3.Dot(transform.forward, directionToPlayer.normalized);
if (distanceToPlayer <= 9f && dotProduct > 0.5f)
{
playerManager.PlayerTakeDamage(-100);
Debug.Log("Player attacked.");
}
else
{
Debug.Log("Attack missed .");
}
}
i have a problem here, animator.SetBool("CloseToPlayer", true); starts attack animation, i am trying to stop during delay
Question: How can I properly release a GraphicsBuffer inside a MaterialPropertyBlock? I can't seem to find a way to access the buffer after the block is created and Unity now warns me about memory leaks every time I quit the game loop
using Unity.Burst;
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;
partial struct SelectedVisualSystem : ISystem
{
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
foreach (RefRO<Selected> selected in SystemAPI.Query<RefRO<Selected>>())
{
RefRW<LocalTransform> visualLocalTransform = SystemAPI.GetComponentRW<LocalTransform>(selected.ValueRO.visualEntity);
visualLocalTransform.ValueRW.Scale = 2;
}
}
}
why is my scale not changing? (When I manually select through inspector, current scale is 0,2,1
and here is the other script
using Unity.Entities;
using UnityEngine;
public class SelectedAuthoring : MonoBehaviour
{
public GameObject visualGameObject;
public float showScale;
public class Baker : Baker<SelectedAuthoring>
{
public override void Bake(SelectedAuthoring authoring)
{
Entity entity = GetEntity(TransformUsageFlags.Dynamic);
AddComponent(entity, new Selected
{
visualEntity = GetEntity(authoring.visualGameObject, TransformUsageFlags.Dynamic),
showScale = authoring.showScale,
});
SetComponentEnabled<Selected>(entity, false);
}
}
}
public struct Selected : IComponentData, IEnableableComponent
{
public Entity visualEntity;
public float showScale;
}
Probably a question for #1062393052863414313
and do what after that
how
you could put a game object at the position the raycast hits, make your camera a child of that game object, then when you press QE you rotate that game object, and the camera will also rotate as a result
How can i make an entity which will have some destroyable parts with they own hp pool (before destroying) but damage dealth to this parts will deal damage to main body too? I cant imagine how to share body hp with this parts
if the body parts are children of the main entity, on awake/start in each body part, they could do GetComponentInParent<YourEntityScript>() so every body part will have access to its script
when you reduce the body parts health, just add a line that also reduces the main entities health by the same amount or however you want it
(Ideally they would have a direct cached reference to that central component rather than finding in parent)
Thank you, it doesn't sound hard at all
I don't have a mob spawn manager yet so i'm not sure how i will spawn them naturally but if i make it with prefab i will give them references
Hi, I'm having a bit of a problem with my WebGL build.
I have a set of Button GameObjects which assign certain values in their Awake, they are controller by a different script which in it's Awake should wait till all buttons are initialized and the de-activate them.
In the editor this runs fine but if I build for WebGL and run in the browser, only 2 of the buttons' Awake is actually called
// this is called from a script Awake
private IEnumerator InitializeButtons()
{
for (int i = 0; i < menuButtons.Length; i++)
{
if (menuButtons[i].GetComponent<TowerHolderButton>().iconSpriteRenderer == null) yield return null;
}
Debug.Log("All buttons initialized");
HideButtons();
}```
There are a total of 6 buttons (as seen in the unity screenshot), but in the browser the message in their `Awake` is logged only twice before that initialization coroutine finishes
show the actual code where the NRE is occurring
however it sounds like you are relying on certain objects having their Awake called before others which is not guaranteed. use Awake to initialize an object's own variables, then use Start to reach out to other objects
Yeah that is just the consequence of the Awake not being executed, it's a different function which references a variable set in Awake
Yeah this sounds like what I'm looking for, didn't really distinguish between the two. So in Start I can safely assume all other MonoBehaviour Awake functions have been called?
yeah pretty much
Okay I'll try that then, thanks
Wow, unsurprisingly that did the trick, thank you very much. Spent a good 2 hours debugging this which was annoying since I could not reproduce it in the editor
anyone know if unity has a replacement for [ModuleInitializer] or the best course of action to replace [ModuleInitializer]?
For a special renderer I need to have mesh data processed in a specific way. So, I have some code that runs when I add a the component that enables this rendering (I use OnValidate) that needs access to the gameobject's mesh data, processes it, makes a ScriptableObject and saves that and then assigns the ScriptableObject to its own field. Is this a reasonable implementation?
Now, this process also takes a while, so I'd like to know if it's possible to get this to run in a non-blocking fashion ( I tried messing with async, but I can't access the objects outside the main thread)
Its not a good idea to modify the asset database in a OnValidate callback, it would make sense to maybe warn the user that they should press a button that kicks off this process or add a menu-command to start it.
you may also want to have a look at Editor Coroutineshttps://docs.unity3d.com/6000.0/Documentation/Manual/com.unity.editorcoroutines.html
Thanks I'll have a look
Also is there a good way to profile editor scripts like this?
You can profile both game and editor scripts with the profiler.
How do I use it to profile an editor script that only triggers once? It's in this frame mode so I'd have to capture the specific frame and by that time it's already captured a bunch of frames where the stuff I want to profile is already gone...
I haven't used it much before sorry
You can increase the frames buffer to hold more frames, or monitor the profiler graph manually and disable recording right after you get the spike that you want to investigate.
If it's async code, maybe make it sync temporary to capture the whole logic in one frame.
Other than that, look at the code, use the debugger, log to the console.
Hello. I have been following along with this tutorial
https://sergioabreu-g.medium.com/how-to-make-active-ragdolls-in-unity-35347dcb952d
So the simulated doll is moving.. just not in the way that it should. It seems that the rotations are messed up
I'm stuck on this part, probably why
How do I set the axis and secondary axis? The numbers seem random to me.
like, is this facing the right way? How do I orient the axes?
What makes them random? Looks like the axis is basically "left" and the secondary axis is "forward"
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Okay so I'm pretty sure this should be simple but I'm dumb so idk?
In the case of my code below here, how would I get the closest object of the ones being ran through in this foreach?
foreach (GameObject obj in itemsInRange)
{
float distance = Vector2.Distance(this.transform.position, obj.transform.position);
}
Before the Foreach make a variable GameObject closestDistance and update that variable each time you run into a gameobject that is closer in distanced from this stored value
Well, probably a variable for both the gameobject and the distance of that object if we want to cache everything.
GameObject closestObject;
float closestDistance;
foreach (GameObject obj in itemsInRange)
{
float distance = Vector2.Distance(this.transform.position, obj.transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closestObject = obj;
}
}```
Can also make a tuple
@dull temple I see it too
Yeah that makes perfect sense, thanks! I'm not used to working with foreach loops 😓
I wonder if Mao sees it
Idk lol
oh yeah
Implemented the stuff tho and it all works perfect, no worries <3
no wait now yall making me doubt it
I'm just using their code there. They're comparing the local object to those in the foreach
Yeah, I was thinking the bug that E pointed out was that the closestDistance was a GO
GameObject closestDistance
oh ok yeah now I see it ;p
I don't know how I overlooked that
And then spotted a non error

I'm going to eep, it's too late
Hey, I am experiencing a problem where when I disable this Movement script while the player is moving, the player doesn't stop moving.
https://hastebin.com/share/imapohuhul.csharp
https://streamable.com/n4l7jp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is the script that disables the Movement script: https://hastebin.com/share/jeyajuzene.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
because your movement script is moving via setting RIgidbody velocity
disabling the script isn't going to reset the velocity to 0
If you want it to do that, add an OnDisable to the movement script which does that
as of now, the velocity will remain at whatever your script last set it to, and stay there until friction or other external forces slow it down
Also what's up with the isPaused and wasPaused variables? They seem to sort of do the same thing but not really?
Also everything that is in your Update function here seems like it should actually just go inside the Pause function
That makes sense, I honestly forgot about the OnDisable class.
there's no reason to have this code running every frame
it's not a class, it's a method
classes are things you define with the class keyword
That's true, I didn't think of that, I just moved the stuff that was in the Update method to their own method, and that method now gets called whenever the player pauses/unpauses or toggles the watch.
Hi , I want to know when main thread is waiting JobHandle.Complete, it will be busy waiting or the main thread will be suspended?
Unknown, the code is closed-source native code.
https://github.com/Unity-Technologies/UnityCsReference/blob/b42ec0031fc505c35aff00b6a36c25e67d81e59e/Runtime/Jobs/ScriptBindings/JobHandle.bindings.cs#L65
I imagine it's just a . Er probably more like waiting on a mutex or semaphorestd::thread::join at some point but we can't know for sure
so uhhh, i booted my project today and was meant with a wall of errors. unity decided not to use UnityEngine.Color by default and is trying to just use Color. how does one get this back to normal? first thing i tried was reimporting all assets but that did not fix it, and i really dont wanna write UnityEngine.Color every time i want to just use Color
Do you have your own Color class/struct perhaps?
no i dont
you definitely do
try ctrl+clicking on the Color word to see where your IDE takes you
i dont
or right click and jump to definition/declaration
yeah it doesn't take me anywhere
System.Drawing perhaps?
no it would say that
thats what i saw on google
Share a script that has an error like that.
it would say "Cannot convert UnityEngine.Color to System.Drawing.Color
it just says Color
and i also thought that too
so you have one in the global namespace
Have you used your IDE to jump to the definition/declaration yet?
yes i do all the time
and where does it take you
Then your ide is not configured
works fine with other things
Share the code and config your ide:
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
also like i said, it was 100% fine last night, and only now is throwing these errors after booting today
i added and changed nothing
Or at least take a screenshot of it, so that we can be sure it's configured
Do you need help or not?
man this is why it sucks to ask for help here, i ask for help and give info and answers but then just get that response.
like i said, my IDE is configured, trying to find the jump to the definition works fine on everything else, but not on this Color. i dont have a Color class in my project, i checked. and this issue popped up after i changed nothing and added nothing. it seems to be unity just having a fit and im asking if people know why unity is having a fit
all i did was boot unity today, and now there are errors, thats why the first thing i tried was reimporting all assets
people always say this, and then it turns out something changed.
It would've been so much faster if you just shared what I've asked for.
Anyways, there's not much we can help you with unless you share the details that I mentioned
You're looking for someone to commiserate in the "unity has ghosts" party I guess? We're interested in just helping actually solve the problem.
nevermind anyways, fixed it by deleting the library folder for a 2nd time
so like i said, unity was just having a fit
There must be a reason why that happened to you and doesn't happen to 99% of other people. And if it did happen, it might happen again. So it would be a good idea to identify the cause.
yes i agree, i plan on trying to recreate it if i can so i can figure out why
i assume its some underlying issue below unity, could be windows having the fit
Or misconfigured ide
hi, not sure if this is the correct channel but, i just installed hub for the first time but the project is stuck at "initial asset database refresh" i'm on mac m1 and none of the solutions on the forums worked for me
does anyone have trouble with delay in their jump in their 2d game? I've been perusing various online tutorials trying to find a solution and no matter what there's a weird delay that won't let my character jump seemingly at random
No. It must be a problem with your code.
is there a spot I can drop that to get it looked at?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
GetbuttonDown in FixedUpdate is problematic
lot of comments there
I don't think you have a delay problem I think you have a missed inputs problem
Input handling needs to generally happen in Update
FixedUpdate is where the physics should go
force of habit from an old-school professor lol
my bad, having a little trouble with the distinction honestly
does that look a little more practical?
it's in the name, fixed happens at a consistent rate regardless of your framerate, update happens as often as your framerate
fixed is better for stuff like physics because of it's consistency between calls, but can "miss" time in between them compared to update by nature of making them consistent
else if(!(Input.GetButtonDown("Jump"))){
Uinput = false;```
huh
get rid of this
this will also make you miss jump inputs
The time to set Uinput to false is when you actually do the jump
Also - "Uinput" is a very confusing name for this variable
how about something descriptive like userWantsToJump
where should I put the set statement in this case?
if(Uinput){
hardbod.AddForce(new Vector2(0f, jump));
Uinput = false;
}// end if
because I tried this and then the jump stopped working entirely
you'd have to show the full code
use a paste site
and/or make a thread
This doesn't match what you just posted
sorry I was trying something else
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pawn : MonoBehaviour
{
private float LRinput;
private bool Uinput;
public float speed;
public float jump;
public float fallSpeed;
public Transform groundCheck;
public LayerMask groundLayer;
Vector2 Gravity;
Rigidbody2D hardbod;
Animator pGrif;
// Start is called before the first frame update
void Start()
{
pGrif = GetComponent<Animator>();
hardbod = GetComponent<Rigidbody2D>();
}// end start
void Update()
{
#region jump
if(Input.GetButtonDown("Jump")){
Uinput = true;
}// end if
#endregion
#region movement
LRinput = Input.GetAxisRaw("Horizontal");
if(LRinput != 0){
pGrif.SetBool("Movecheck", true);
}// end if
else{
pGrif.SetBool("Movecheck", false);
}// end else
if(LRinput > 0){
transform.eulerAngles = new Vector3(0,0,0);
}// end if
else if(LRinput < 0){
transform.eulerAngles = new Vector3(0,180,0);
}// end else if
#endregion
}// end Update
void FixedUpdate()
{
hardbod.velocity = new Vector2(LRinput * speed, hardbod.velocity.y);
#region jump
if(Uinput){
hardbod.AddForce(new Vector2(0f, jump));
Uinput = false;
}// end if
if(hardbod.velocity.y < 0){
hardbod.velocity -= Gravity * fallSpeed * Time.deltaTime;
}// end if
#endregion
}// end FixedUpdate
bool isGrounded(){
return Physics2D.OverlapCapsule(groundCheck.position, new Vector2(1.65f, 0.46f),CapsuleDirection2D.Horizontal,0, groundLayer);
}// end isGrounded
}// end Pawn
You probably want an impulse force for a jump.
What is jump set to? it's probably too small for a non-impulse force
Also use Debug.Log to double check your code is running when you expect it to
300
which I'm turning down now because this iteration seems to react significantly to that setting
nvm that was 15 but the gravity scale was at 1
you'll want impulse for a jump.
hardbod.AddForce(new Vector2(0f, jump), ForceMode2D.Impulse);```
and to reduce the value by about 50x
Maybe someone can help I have been getting the error NullReferenceException: Object reference not set to an instance of an object when I try to attack with nothing equipped I have tried everything to make it so it doesnt even run that code when you have nothing equipped but it still throws that error
public class WeaponAttack : MonoBehaviour
{
public float attackRange = 2.0f; // Range within which the attack can hit
public LayerMask targetLayer; // Layer mask to specify which objects can be attacked
public InventoryScript inventoryScript; // Reference to the InventoryScript
private float attackDelay = 2.0f; // Delay between attacks
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
if (inventoryScript == null)
{
inventoryScript = Object.FindFirstObjectByType<InventoryScript>(); // Find the InventoryScript in the scene
}
}
// Update is called once per frame
void Update()
{
if (inventoryScript == null)
{
Debug.LogWarning("InventoryScript is not assigned.");
return;
}
// Update the attack delay timer
if (attackDelay > 0)
{
attackDelay -= Time.deltaTime;
}
if (Input.GetMouseButtonDown(0)) // Check if the left mouse button is pressed
{
if (attackDelay <= 0) // Check if the attack delay has elapsed
{
if (inventoryScript.playerMovement != null && inventoryScript.playerMovement.enableMouseLook) // Check if the mouse look is enabled
{
PerformAttack();
}
else
{
Debug.LogWarning("Cannot attack when the mouse look is disabled or playerMovement is null.");
}
}
else
{
Debug.LogWarning("Cannot attack yet. Attack delay in progress.");
}
}
}
private void PerformAttack()
{
if (inventoryScript != null)
{
if (inventoryScript.equippedItem != null)
{
// Get the damage value from the equipped item
float damage = inventoryScript.equippedItem.template.damage;
// Perform a raycast to check for a target within the attack range
RaycastHit hit;
if (Physics.Raycast(inventoryScript.playerMovement.cameraTransform.position, inventoryScript.playerMovement.cameraTransform.forward, out hit, attackRange, targetLayer))
{
// Check if the hit object has a PlayerHealth component
PlayerHealth targetHealth = hit.collider.GetComponent<PlayerHealth>();
if (targetHealth != null)
{
// Apply damage to the target
targetHealth.TakeDamage(damage);
Debug.Log($"Attacked {hit.collider.name} for {damage} damage.");
// Reset the attack delay
attackDelay = 2.0f;
}
else
{
Debug.LogWarning("The target does not have a PlayerHealth component.");
}
}
}
else
{
Debug.LogWarning("No item is equipped.");
}
}
else
{
Debug.LogWarning("InventoryScript is not assigned.");
}
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and where are you getting it, exactly
my bad I messed up the format
as in, what line
61 and 40
I am looking at the console
screenshot the error you're talking about
it only throws one error though
and see the "large code blocks" section of the bot embed
im not gonna count 60 lines lol
ok so yeah the error is from line 61
the other line mention is just part of the stacktrace, where the function was called from
Like this then: https://paste.mod.gg/ibfmizrbijhc/0
A tool for sharing your source code with the world!
yeah it should be stopping that from running when it is though
oh wait
you're checking inventoryScript and inventoryScript.equippedItem, but not inventoryScript.equippedItem.template
in the situation you mentioned, if you expect equippedItem to be null instead (and template to never be null), try investigating what happens when you aren't holding anything
all good now thanks again
How to reference the default Unity project assembly in my Test project for which I created assembly definition file?
The main project is not present in the Test project assembly definition file and nothing happens when I add Assembly-CSharp in the list of references lists in the asmdef file.
How do I use the classes defined in my main assembly inside the test test assembly?
you'll need to put that code you want to reference into its own asmdef too
Ok, so I added asmdef file to Scripts folder and named that assembly Scripts.
Then this Script assembly started throwing errors about different assemblies like UnityEngine.InputSystem
After I added all the assemblies that I use manually to this Scripts assembly
The project compiled
Then I added this Scripts assembly to the Test assembly
And it compiled and tests work
But now the problem is that I have to manually add all the dependencies: all the default Unity dependencies that are referenced in the main assembly
Do you have a project at hand that is tested and do you manually add all the assemblies or is there a better solution to test a project?
yeah you need to add the dependencies one by one to the assemblies
there's not really a way around that
I just dropped that asmdef file into the Assets folder and the whole main project was replaced with my Scripts assembly:
And it compiled
And the test ran
scripts on inactive objects still recieve events right?
Some events, yes
But not Start and not Update
But I think they still receive the collision events from the collider component and other
So if you want to stop receiving collision events, you need to disable the collider, not the script where you defined the collisision handler
I mean custom events I create and subscribe
btw when you start using asm defs, the "Editor" folders no longer auto put code into an editor assembly so you have to make asm defs yourself to do this.
so its not wise to slap one in Assets cus most packages/plugins dont use asm defs as they should
So what do I do? I just want to have the test project and not have to add every single assembly manually.
test project? make asm defs where it makes sense to (e.g. one in Editor, one in Scripts, and ones for editor and runtime tests)
im just warning you that putting one in Assets may screw you over later but you do you 🤷♂️
not implementing asmdefs correctly can slow down your compile time
also it makes no sense to only use asmdefs to reproduce what unity does anyway (split plugins, editor & scripts into separate assemblies)
was just an example of where to start. I dont remember if tests must use them but if so then you will need to add them to reference your other code.
I don’t understand your point here
if you have some plugin/addon that presumes that Editor folders automatically work but you put an asm def in Assets/ this will break them all.
Ohh you meant Assets like very specifically that root folder understood
Yep, test project requires to create a separate assembly for the Scripts folder: I can't reference the main Assembly-CSHarp project in the Test project.
Yea tis a limitation of them, asm defs cannot reference those. Tbh you are probably fine with an asm def in where you keep most scripts
Even when I put the asmdef file in the Assets folder, while it replaces the main project, it still doesn't automatically reference all default assemblies like Unity.InputSystem, like the Assembly-CSharp project does.
I just want to reference everything that that main project references
So that when I use more and more assemblies, I don't have to add them manually and then when I install additional assemblies like Cinemachine, I don't have to manually add them either.
its just how it works, you manually add the asm def references, its not hard
I.... thanks, I found where I have fucked up
literally method of unsubscribing onDisable
what
It's not hard, but convoluted. Once the project grows and let's say I have 5 solution assemblies and I add a plugin like Cinemachine, now I have to go and add it to 5 asmdef files, so that I don't have to do it later.
Well, I can go through the list of References in Visual Studio and reference all the assemblies that are referenced there, then maybe create a template file in Visual Studio to automatically create an asmdef file for assemblies that do this.
Will work for all the Unity.* assemblies but not for plugins.
ive made do for years but dont blame me for how it works
Ofc, Rob, I appreciate your advice
To not put it in the Assets folder
And like at least that's how people actually do it
5 asmdef defs probably shouldn't all be referencing cinemachine.. the "best" way would be for all camera related stuff to be in 1 of them
I forgot to remove the method where I unsibscribe from the event inside OnDisable() event
should I move this to #💻┃unity-talk?
If it’s not code related, yes.
You ever rely on singletons a little too much?
Nope
Especially when networking. Tempting to just make everything local client related a singleton
Imo when it comes to games it's probably a little more acceptable than in backend programming
Use them only when there's a need, not for every little thing that leads you to thinking "I'm doing this too much"
Feels good though must admit
No reference hell just grab/set whatever you need
Though I suspect the next statistically best response would be "if you're encountering reference hell you're doing something wrong to begin with"
Nice to turn off your brain every now and then and just make a mess
Singletons are fine if you're working by yourself or in a small team on a small project, but it scales terribly because suddenly you have 25 different people's code all touching the same singleton classes and when one thing breaks, everything breaks
True
I don't see how singletons increase the number of people touching a particular piece of code or not 🤔
Don't confuse what objects do at runtime with what developers do at code time
Using singletons doesn't mean ignoring the Single Responsibility Principle
I can program software, but sadly I can't program people. Best I can do is architect my code in such a way that it encourages good coding practices
Hello everyone, I have a question about the Unity editor and public variables
!ask away
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have a public class with many public properties. I have another class(MonoBehaviour) which has a public variable of the first class. I can see the first class as a variable that I can change in the second class.
I want to change the default properties of the first class but ONLY as the public variable of the second class.
Example:
public class h1 {
public int n1 = 0;
public int n2 = 6;
}
public class h2 {
public h1 hello;
}
I want "hello" to have n1 = 1, instead of 0, by default, but only when we are talking about the h1 variable when it is the public variable of h2.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Write a Reset function for H2
Hmm, seems very good! another, related topic, I want the class h1 to change these defaults with many other classes that use it as a public variable, so I have h2, but let's say I have h3 and h4 and so on that do the same thing as h2, but I want different defaults for each of h1.
Two questions on this front:
- Should I then put the config reading code for the defaults in the reset function of h2, h3, h4, etc?
- Should such config files be a single config file for many different objects of a similar class, or should each class, h2, h3, h4, have its own config file?
Good point actually
If there's a single thing the singleton does, what are the odds two people would need to urgently work on it at the same time
Is there a good place to ask questions about Unity Test Framework? Or is in here fine?
I saw something yesterday and would like if someone can explain any differences. I saw someone use in code "public TMPro.TMP_Text myText;". They had multiple of these in the script. I always use "using TMPro;". I know they do the same thing. Which is better?
it's up to you, it's just a style choice
The full path can be useful if you have pragmas that execute different code when TMP is available or not (it localizes the dependency a bit), but it’s not necessary.
I don't see anywhere specific to post Unity Test Framework stuff so I'll post my question here. Following the Unity documentation, it says to create an assembly definition in the Tests folder, and then create your test scripts in there too. I'm confused though what the purpose of the assembly definition is because I see where others have created tests in folders with no assembly definition, and the tests still seem to work fine. What is the purpose of the assembly definition we're making?
Tests have dependencies on libraries that a (release) build will not need.
Ah so the tests will work in the editor, but without the assembly defs, it'll also bring those dependencies along in a build, just causing unnecessary bloat?
Bloat, security issues, all sorts of things.
Ah ok cool. Thank you!
You can think of testing as a separate platform.
Thank you
in a package.json file because the Package Manager doesn’t support Git dependencies between packages. It supports Git dependencies only for projects, so you can declare Git dependencies only in the project’s manifest.json file.```
why ._,
please don't crosspost
anyone got a good vid/article on how addlisteners work with buttons? I need to add one when instantiating, then when its called pull a string attached to a script on the button, different for each button but opening the same script. documentation on addlisteners is not great, so any vids/articles/suggestions would be greatly appreciated
Any decent way to check if a UGUI slider is being held?
what exactly are you trying to find out in how it works? its just an event thats invoked when clicked
i need to have it also call the string from the button when the event is invoked
When you add a delegate you can add a member function or a lambda. Its a common concept also shared with normal c# events.
you can make your own script have an event to "pass" the extra data, let me write an example...
what does that have to do with addListener? also this doesnt make a ton of sense
"call the string" a string is not something you call
and what string are you trying to get
public class SpecialButton : MonoBehaviour
{
public event Action<string> OnClick;
[SerializeField]
Button button;
[SerializeField]
string data;
private void Awake()
{
button.onClick.AddListener(() => OnClick?.Invoke(data));
}
}
sorry i'm not great at explaining things. the button is a ui image that is instantiated, then the addlistener makes it so when it's clicked it calls a certain function. this function has to pull the string that is inside a script attached to a button to set the parameters for the function to activate with
you can replace the event with a UnityEvent if you prefer but the concept is the same.
sorry I'm not sure how that works. i'm not very good at this stuff. still trying to learn a lot
what rob wrote above is basically rather than subscribing to the button, subscribe to an event on your own component.
this should really be in #💻┃code-beginner if you're a beginner. gives us a headups of how indepth to explain also
The script has defined its own new event that you can subscribe to. The script adds a listener to the unity button to call our new event when the button is pressed. It also gives the data as extra data in the event.
e.g. GetComponent<SpecialButton>().OnClick += (string data) => Debug.Log(data);
its similar to button.onClick.AddListener in how we can provide some code to execute when the event is triggered.
if I have a script attatched to a gameobject that also has a meshrenderer component, is there a way to kind of link a function in the script to trigger when the meshrenderer is enabled/disabled WITHOUT having the script manually check it constantly/frequently? I cant have the script checking it constantly, cuz this needs to scale to thousands of objects/instances of this script
Whats turning the meshrenderer on?
it could be anything, user, unknown script, etc.
WHAT toggles it I dont have control over
so I was wondering if there was an api or something I dont know about that can cheaply "listen"
No, the best option is to make whatever turns it on or off also do the other thing.
What's the context here and why don't you have control over it?
cuz since i am developing something for other to use, It needs to be as flexible as possible
a lack of control doesn’t seem flexible
You can’t watch object activity in an event based context as an outsider afaik
yeah thats about what I thought
Ideally you’d have something in the middle of this
If you provide more context a less abstract answer could be offered
I think you would provide your own abstraction here - another script. You could have people call functions on or enable/disable that script. That script would then disable/enable the MeshRenderer as well as, e.g. firing off a UnityEvent or doing whatever it is you need done
yeah thats what I thought I might have to do
but that seems really inconvienant for other users to change all instances of enabling/disabling that to use a different function
to be fair to those users, they probably didn't expect enabling or disabling a MeshRenderer to have whatever side effect you're about to add
but yes, that's kind of how refactoring software works - you need to switch over users of the old thing to the new thing
im not quite sure how to
I have script B that acts as a "parent"/container to a bunch of script A's
each script A is gaurenteed to be in a gameobject with a meshrenderer
when the meshrenderer gets disabled, I need to send a signal to script B that a specific script A's state has changed
fair enough
well certainly it could just check them all each frame
if there's not too many that's not that big of a deal
MeshRenderer’s being toggled should be the result of a state change, not the state change itself
but otherwise - B needs to listen to the events of the As changing
ok no wait
script A doesnt get toggled itself
its in a gameobject with another component, and that other component(meshrenderer) gets toggled
script A then needs to send a signal to script B to update
yeah I know what you're asking
I'm describing the hyprothetical scenario with the new abstraction in place
without that you need to just check periodically
ah
Would be kinda nice if Unity did let you listen to activity like that tho, even though in most situations it’s avoidable
it would be unecessary overhead the vast majority of the time.
fair
also if I have like 5000 small buffers(1 buffer for each mesh that stores its triangle data, I cant know the AMOUNT of these buffers I have)
is there a super fast way to combine them all into one large compute buffer? cuz currently I am using just a compute shader that gets dispatched for each addition of small buffers into large buffers, but it takes about 50ms this way
better to rewrite that to use one large buffer
I cant do any pre-compaction or merging
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
is this because you don't know how big each buffer will be?
No, it’s because I need to be able to isolate them
can't they simply be isolated by their location in the buffer?
can Mathf.Pow not take a negative exponent?
everytime I try to use it with a negative exponent I just get 0 instead
What's the base?
show what you passed in
also show the code
float multiplier = 1f + (90f * (1f - Mathf.Pow(2f, -angle)));
where are you getting 0
Do:
Debug.Log($"Pow output with angle {angle}: {Mathf.Pow(2f, -angle)}");```
Mathf.Pow(2f, -angle))); always returns zero, at least for angle values 0 < x
just a sec
let me test that - I'd be surprised...
Pow output with angle 45: 2.842171E-14
if these are euler angles, like where angle can be 50
2^-50 is an incredibly small number
so it's not zero just, very very small
did you put that into your calculator, thats how math works
i expect the 45th root to be tiny
how can i code shaders for unity without shader graph? i would prefer code them by myself because i already have experience using gpu stuff. is there a good tutorial about shader coding?
my calculator is giving me a different result though? when I try it out, I get 1
try just 2^-45 in your calculator
google agrees with Unity
because - as you'd expect, the 45th root of 2 is very small
a sorry
i dont think 45th root is the correct term, i have no clue how to type that out in discord so i just put it in desmos
it's 1 / 2^45
yeah I mispoke
its crazy how long that took me to write in desmos
it's 1 / really big number which = really small number
Yes but the total buffer length is always changing, so I gotta recreate it
That's what a list is for - and/or preallocating to a larger size - and/or enforcing limits
Does Resources.Load() create a new instance of the object, or a reference to the object in the game files?
specifically ScriptableObjects?
ie: if I use Resources.Load() on a ScriptableObject in my Assets and modify the values, does it update those values on the ScriptableObject in my Assets, or am I creating a new instance of that ScriptableObject and modifying it's values?
So, the answer is a bit of column A and a bit of column B. No it doesn't update the values on the object, because Resources.Load just gets a copy of the object in memory. Are you using your scriptableobject to store data at runtime?
yes I am using ScriptableObjects to store data at runtime
Well, you can't. They're immutable.
You can use the AssetDatabase namespace to modify them while using the editor, but that won't build to the player.
What you want to do is create a system to store your data and only use ScriptableObjects for the initial conditions of whatever you need. That's not a place to put your game logic.
Well what I'm doing is creating an instance of them in my Assets folder, then I have references to them and modify their values at runtime.
I know this doesn't save after the game stops running.
This has been working fine for me so far. However I'm working on my save system (where I pull data from that ScriptableObject) and wondering if I can just grab it from Resources.Load()
Ah, alright. I see. Still, the scriptable objects (on disk, accessible through Resources.Load<>()) aren't really mutable memory. You could load a resource and then store it as a UnityEngine.Object somewhere and edit that, but you can't write over the original object. It's like a prefab in that way.
They're essentially stateless beyond holding cookie-cutter data written at compile-time.
scriptable objects are mutable. the changes just don't persist across multiple sessions in a build like they do in the editor
Ok that makes sense. I will just have to store a reference to the ScriptableObject in my Assets folder somewhere rather than using Resources.Load(). Thank you!
Right, I knew that I wasn't entirely accurate with my explanation, but I was "right enough" that they aren't persistent.
Sorry, "mutable" wasn't the word. boxfriend explained it better.
yea I understood what you meant!
but could totally see how it'd be confusing for a newbie
It is. I learned exactly this same lesson at one time, but understanding this, I got a better idea of what problem ScriptableObjects solve.
@mystic jetty What you could do is make a self-serializing scriptableobject. 👀
would that work with BinaryFormatter?
honestly I haven't looked into making my own serializable data. I'm just serializing basic types into a file via BinaryFormatter.
Then deserializing those types and plugging those values into my ScriptableObject at runtime
I imagine it should work. You could try with JSON to first see what you're dealing with.
you should avoid BinaryFormatter like it is the plague
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
Interesting. I didn't know this. However what is the actual worst that can happen with an offline single player game?
that's covered in the article.
This scenario can be leveraged to nefarious effect. If the app is a game, users who share save files unknowingly place themselves at risk. The developers themselves can also be targeted. The attacker might email the developers' tech support, attaching a malicious data file and asking the support staff to open it. This kind of attack could give the attacker a foothold in the enterprise.
ah I missed that sorry.
good point. Ok I'll look into converting to a JSON system. BinaryFormatter is a pain in the ass anyways
What's nice about using JSON for a serializer is that there are some easy ways to flag the fields that you need saved using attributes. I think that's with NewtonSoft, but I don't actually recall which package I usually use.
how's JsonUtility?
Honestly, I forget which one is which, but I'm thinking of one of those. I think I prefer Newtonsoft, but can't exactly recall the differences.
json utility is limited but fast and uses unity's built in type serializers, json.net (newtonsoft) is the full featured convenient option that needs a bit of massaging to work with unity types. Its generally recommended to use json.net (unity packages themselves use it frequently and its offered as an official unity package). you can find converters for unity types on github/openupm.
thank you
Is there a way to sample an animation clip's positions and rotations without animating a gameobject?
Grok gave me... whatever the hell this is. Surely there is a simpler way.
I just need a buffer of the poses from clip at frame zero. I didn't think it would be so hard.
First of all, an animation clip can contain many different animated properties, that are not necessarily position and rotation. Hence the iteration that the ai suggested.
And second, at runtime you can't do even that. The best you can do is apply the animation to a dummy object and check it's position/rotation.
This code is not even gonna compile, since AnimayionUtility is in the editor namespace, and possibly other errors.
why is the Linq IEnumberable<T>.ToList() supposedly so much worse than simply casting the IEnumerable<T> to List<T>?
at least it is according to the roslyn analyser inside project auditor, the unity package
knowing Linq it probably generates a ton of garbage somewhere
so is it perfectly fine to just cast? what am I losing?
Yeah, .ToList/Array and such usually allocate a new collection instance.
Casting = getting the real type of an object. Allocating is creating a new object with the same data.
Not all IEnumberable<T> are List<T>.
I'm talking about the IEnumerable<T> that comes from using the linq .Where on a List<T>
is that one fine to cast?
Try it and see 😄
It's no longer a list after you use .Where.
ToList() will resolve the whole enumeration sequence into a list right then
ToList guarantees a new list is created
really this is not an apples to apples comparison
The question is based on the false premise that the two are interchangeable.
Well? How can I do this then?
The way I explained in the second paragraph.
What are you trying to do anyway? What's the purpose of doing this?
Reverse ragdoll, smooth transition from physics to animated state
I need to get a sample of what to lerp towards
If I'm doing this, I might as well just sample the clip on the current gameobject and reset the pose afterwards.
I would rather not do that
What people usually do for that is have several rigs. One for animation, one for physics and one where they blend between the two. Or they somehow do blending on the physics rig.
If it's some local ragdolling(like staggering on hit), then you can probably do it with one rig. Just apply displacement to bones in late update or something.
Are you talking about active ragdolls?
What do you mean local ragdolling? How is that local?
I don't get it
The goal is to make him transition to the first frame of the getting up animation and then play from there
Instead of sharply cutting to it
Like when only a certain part of the ragdoll is affected by force
Then you'll need 2 rigs for that. One that plays the animation(and is not rendered) and one that is rendered that you lerp between physics and animations.
With that setup, start playing the get up animation, pause the animation, then lerp the visible rig from it's current state to the animation state, then unpause the animation and keep the rigs synced.
Well at that point I'd just do this, I don't want the overhead of spawning another rig or keeping it there for no reason.
Is there no way to just sample the necessary poses from the animation clip?
No. Not that I know of
Alright. Thanks.
So I'm running into alittle bit of a problem, with my mouse movements.
I'm trying to move the SelectedItem slots with my mouse wheel but for some reason, the game acknowledges that it's meant to move but doesn't actually move. I must also say that everything works with the hotkeys it's just the mouse wheel.
The mouse code is in ItemSlot.cs.
Code:
https://paste.mod.gg/lqqwmqccoqoy/0
These are the 2 deubg statment's I get:
Scrolling to slot 0
UnityEngine.Debug:Log (object)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:162)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
Selected slot 0: ItemSlot_2
UnityEngine.Debug:Log (object)
ItemSlot:SelectSlot (int) (at Assets/ItemSlot.cs:134)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:163)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
A tool for sharing your source code with the world!
is Firebase the only best backend for a WebGL game, or are there better alternatives???
Wdym by a "backend"? WebGL games in themselves don't require a "backend"
i mean nosql database
(no)SQL database doesn't have to be remotely hosted. But if you really need to, there should be many different solutions, including your own database server.
well it's just a simple game with a leaderboard so creating my own database is over kill. do you have links for setting firestore on a web gl game. All i can see are for android/apple set up, no webgl
In the simplest form you'd just make http requests without any sdk.
There seem to be some WebGL integrations/wrappers on github that make it simpler for you though. Try googling WebGL integration of firebase. Or check the firebase docs on how to access their rest API via http requests.
making a little server with asp.net that stores the leaderboard as a json file and publishes that to the client with some fake security (since this isn't a serious project anyway) would be trivially easy
Thanks for the tips, but I'd rather use Firebase/Firestore instead of doing everything from scratch. If anyone has a link to a decent tutorial on integrating Firestore with a WebGL game, please let me know. Paid or free tutorials are both fine.
Did you try googling? It finds YouTube videos and GitHub repositories right away.
I did, most of them are old and outdated.
Been searching for days but can't find a decent one. So I went here. I'll keep digging tho
Outdated in what way? Do they cause errors? What kind of errors? Did you try to troubleshoot them?
yes they are not working on my end
i did
And? What kind of issues are you getting? What solution did you try?
Features like that would often require you to o some fixing/adjusting yourself.
yeah, interesting, thanks for the help!
https://gyazo.com/3da75ff0b8c9d461519ba649380526f7
heya, I have a compute shader that I use to sample points on my terrain mesh (per triangle) and generate grass
it's almost perfect, but I have this flickering issue if I let grass spawn on slopes. the problem seems to be with edges with differing normals (aka slopes), and I'm having some trouble fixing it. I was hoping someone could provide some insight
float2 bary = (id.xy) / gpt;
// Fold the square [0..1]^2 into the standard triangle domain
// If s1 + s2 > 1, reflect across the diagonal to stay inside the triangle.
if (bary.x + bary.y > 1.0f)
{
bary.x = 1.0f - bary.x;
bary.y = 1.0f - bary.y;
}
float s1 = bary.x;
float s2 = bary.y;
float s3 = 1.0f - s1 - s2;
// Actual world position from barycentric combination
float4 pos = float4(
s1 * v1Pos +
s2 * v2Pos +
s3 * v3Pos,
1
);
float4 clipPos = mul(_VP_MATRIX, pos + float4(_Transform, 0));
uint isInFrustum = FrustumCull(clipPos);
if (isInFrustum == 1)
{
float3 nm1 = _PlacementNormalBuffer[triId1];
float3 nm2 = _PlacementNormalBuffer[triId2];
float3 nm3 = _PlacementNormalBuffer[triId3];
float2 uv1 = _PlacementUvBuffer[triId1];
float2 uv2 = _PlacementUvBuffer[triId2];
float2 uv3 = _PlacementUvBuffer[triId3];
float4 col1 = _PlacementColorsBuffer[triId1];
float4 col2 = _PlacementColorsBuffer[triId2];
float4 col3 = _PlacementColorsBuffer[triId3];
float3 normal = float3(
s1 * nm1 +
s2 * nm2 +
s3 * nm3
);```
How to get refrence to a scene project-wide.
SceneManager API only looks through loaded scenes which is unhelpful,
Asset Database's LoadAsset<T> does not support direct boxing to Scene type. Is there any other ways around this ?
thats cause Scene is a struct for inGame
if you want the actual asset of the scene file its SceneAsset type
On it yeah, Thank you.
Sorry, could you tell me some more about staggering on hit? I was looking for a way to do this that wasn't some stiff animation. I already have an active ragdoll system, but keep it kinematic unless it falls
Well, you could calculate(or simulate, but you'll need an extra rig) an offset of the bones in the area of the hit, and then just apply that offset to the bone position in late update.
Yeah, you can dislocate an arm or any other bone.
What I mentioned has nothing to do with rigidbodies.
Unless you're going for 2 rig setup
But that's dislocation of a limb and not a reaction to getting shot or something
My rig can transition to and from a ragdoll state
I don't understand what a second rig has to do with this
I am making an editor tool and I have been using raw Scenes up till now...how "bad" is it lol
It works tho ...
wdym "how bad is it " ?
Whenever I need a direct refrence to the asset I have to convert between these types because datastore has a GUID and a path to scene, path is useless but I can reconstruct it from GUID. System involes loading / saving / moving scenes around in files.
What is a reaction to getting shot? It's moving the area of the body where it was hit back a little bit, right? This exactly what this approach achieves.
With a second rig you can simulate forces applied to the body and blend between this simulation and actual animation.
I know this question is inherently cooked but;
If a prefab has a serialized reference to another prefab, when you instansiate it the reference is still pointing to the prefab "asset". This is chill
If a prefab has a serialized reference to itself, when you instantiate it the reference will point to the instantiated version of itself. Is there non awful way I can avoid this?
(no could be a valid answer)
You sure? I'd imagine it would point to the asset instance
I assume it points to itself the same way a reference to a component on itself would also reference the newly instanced version
as its in it's own scope
Well, if you want the prefab instance, make your own static that binds the asset to that new instance after instantiating
I can't
because not all usecases involve instantiation (eg. in-scene placement)
hence why I'm looking to do this 😛
uhhh, ok how about a PrefabManager singleton and each instance in Awake() will access its lookup table and find its prefab reference
can you elaborate on lookup tablew
Actually, it would need to be done in OnValidate because it'll lose that prefab reference in Awake
Or, ID the prefabs yourself and the PrefabManager lookup table will return the reference of the ID
You can use AssetDatabase and use editor IDs, but not during the runtime so you'd have to use your own GUIDs
well, you wouldn't need the table if you do it via OnValidate(), only during the runtime would you need to use the singleton
So I'm running into alittle bit of a problem, with my mouse movements.
I'm trying to move the SelectedItem slots with my mouse wheel but for some reason, the game acknowledges that it's meant to move but doesn't actually move. I must also say that everything works with the hotkeys it's just the mouse wheel. Also when I use the hotkeys the selectedItem shows as it's selected.
The mouse code is in ItemSlot.cs.
Code:
https://paste.mod.gg/lqqwmqccoqoy/0
These are the 2 deubg statment's I get:
Scrolling to slot 0
UnityEngine.Debug:Log (object)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:162)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
Selected slot 0: ItemSlot_2
UnityEngine.Debug:Log (object)
ItemSlot:SelectSlot (int) (at Assets/ItemSlot.cs:134)
ItemSlot:SelectNextSlot (int) (at Assets/ItemSlot.cs:163)
ItemSlot:HandleSlotSelection () (at Assets/ItemSlot.cs:116)
ItemSlot:Update () (at Assets/ItemSlot.cs:57)
A tool for sharing your source code with the world!
slot 0 is called ItemSlot_2?
allSlots = FindObjectsByType<ItemSlot>(FindObjectsSortMode.None); probably better to have a centralized manager for all the slots and just assign this in the inspector
In fact looks like inVentoryManager also has an array of the slots?
There should be one and only one thing managing the slots
Did someone tried to bake lightmaps for prefabs with this script? https://github.com/Ayfel/PrefabLightmapping
If there is exist other method to use lightmaps for prefab?
Because that script runs error “Trying to set shader on material variant”
it's overloaded for Unity objects, it checks if the object was destroyed too
Ah gotcha
i don't think it's that expensive really, but it is more so than just a pointer check
I thought so too, but maybe there is something better to use than != null, idk
if you know it'll only be null or not-null and never a reference to a destroyed object, you could write it as x is not null or !ReferenceEquals(x, null), but i expect you'd have to have a lot of them before it made even a small performance difference
Yes that is my case exactly, don't think it matters but good to know the idea 👍
Should you have different [System.Serializable] Save Data for every other object or just one save data for every object?
Example of what I mean:
Game Save Data: Consists player's collected coins
Unlocked Save Data: Contains whatever player has unlocked in the game
OR
Universal Save Data: Contains all the data and one constructor to initialize them as well
Depends on the scale of the game and what makes sense for your implementation
Scale is big
Or moderate for being grounded
Thankyou 😭
I couldn't get an answer anywhere
It works perfectly now
Probably easier to maintain and track if it's split up into appropriate categories/ sections
Got it
...Okay I don't get it
Seems like one script's start executes before other script's awake
is this even possible or I messed something up?
they both are on objects existing in the scene
when I start the active object sends debug log from start faster than inactive from awake
Inactive objects don't run any Unity methods
you tell me Awake doesn't run on inactive objects?
it runs before OnEnable as soon as you activate them
Too lazy to get the most recent docs https://docs.unity3d.com/540/Documentation/Manual/ExecutionOrder.html
Awake: This function is always called before any Start functions and also just after a prefab is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active.)
Now you know ⭐
I am very confused but I understand now
awake runs immediately when you instantiate an object. if that object is a DISABLED prefab or other DISABLED object you use as template, it will not run until you enable it
so horrible to realize it so late
here I go making spaghetti initialization once again...
being nitpicky but i assume it doesn't run immediately when you instantiate an object because of the instantiation itself but because instantiating an enabled object "enables" the new object instantly
maybe thats a nice way to memorize this behaviour
otherwise it seems "complicated"
if you wanna be very cursed you can use this to do weird shit like
MyComponent myPrefab;
Spawn()
myPrefab.SetActive(false)
MyComponent spawnedInstance = Instansiate(myPrefab)
spawnedInstance.SomeSpecificSetupNeededOnYourInstanceBeforeItShouldDoStuff()
spawnedInstance.SetActive(true)
myPrefab.SetActive(true)
this can be very useful when restoring from a serialized state
I just mention it to point out it's not two reasons awake happens instantly but one reason (a object being set to active for the first time) just being caused by two different things (setting it to active explicitly or as a result of instansiating an active object)
practically it's irrelevant but might help understand what's actually happening there
#💻┃code-beginner pls
no begging, crossposting or advertising
? wdym
just asking for a little help
thought code beginner was for helping ppl
this is not #💻┃code-beginner , this is a different channel which you used for advertising your other post
huh
where
when I click it it takes me to code begginer @cold parrot
it's been like 5 mins since you first posted. Patience
No I meant like, How is anikki being taken to another website when I do #💻┃code-beginner ? @mental reef
OHHHHHHHHHHHHHHHHHHHHHHH WAITT JUST GOT IT
Hello, I am getting memory allocation errors. I understand why they originated in the first place, but do not understand why they retain.
The origin of this was an exponential recursion loop (seen in image2), completely my fault for forgetting how big exponentials are.
Any tips on how to fix the error? i alr have some ideas on making the script not do what it did
are you sure this is due to your code? Is this executed in a burst job? If its managed code then this should not apply in any way.
If there is any unsafe code relating to this then share it
im not too experienced with what that means, but i can share the entire script, one sec
then means its not from your code. Unless you are using unsafe or burst or some native collections then GC will take care of it all
Why? native memory allocation can easily "leak" but in normal c# the GC cleans up memory for us
okay nvm icant send my entie script, but thats weird i dont think im in unsafe mode
yea its probably some other thing and not your fault. Any useful information in the errors?
script is too big, i could use a paste bin in a min
let me check
sorry for the slow replys btw, using a crappy school pc rn so its hard to test things
how do you know the leak is caused by that code?
didnt have the leak till i ran that method specifically, but i could be wrong
Yea I think it's some other things not relating to your code. It mentions TLS anyway
in any case, refactor the code to eliminate the recursion
and apply some proper formatting/style
Please at least make a local variable for Cell.Key + new Vector2(x, y) lol
lmao alright
It's used 10 times here :p
will do
you are also mixing integer based logic with storing floats
huh? where
the only thing saving you there right now is unity's Vector types silently doing an .Approximate comparison of vectors
oh with the vectors
Could just go with Vector2Int as key
Thanks for the advice
Just out of curiosity, how many recursions do you get before the error?
Well you are allocating a new Vector2(x,y) a bunch of times but it’s the same value so why not alloc it once for each loop ?
vectors don't allocate
stack allocation moment
ofc the stack explodes, but not because he's using local variables
the recursion needs to be removed anyway
He is not using local variables, unless you think the compiler is smart enough to put the 10 new vectors he is using into a single variable
Does anyone remember that cool and new rendering feature that acts similar to drawing instanced meshes but takes a culling function?
I swear I've seen something like this
Batch render group ?
The brg has a OnPerformCulling that you submit your draw commands in
probably not
and this is why
Wdym probably no? They have to allocate somewhere
registers exist
So ?
they might not even get to the stack
local variables are allocated to the stack
these aren't in variables, as you say
You think the compiler pushes a single value to a register and reuses it
Could be compilers are wicked smart. I dont have the time to look at the machine code this will produce
no, it probably gets set multiple times
Me personally I would not write that code the way it is written
but i'd guess not on the stack
And I think the advice I gave is sound
but really it wouldn't make a difference for perf
i agree with your proposed change, but not for the reason you gave; it'd be more readable and less mistake-prone
I think that depending on his loop and recursion count my change will indeed save the stack but that’s just me
this is a ctor of a vector3 struct.
public struct Vector3
{
public float x;
public float y;
public float z;
public Vector3(float a, float b, float c)
{
x = a;
y = b;
z = c;
}
}
C+Vector3..ctor(Single, Single, Single)
L0000: vmovss xmm0, [esp+0xc]
L0006: vmovss [ecx], xmm0
L000a: vmovss xmm0, [esp+8]
L0010: vmovss [ecx+4], xmm0
L0015: vmovss xmm0, [esp+4]
L001b: vmovss [ecx+8], xmm0
L0020: ret 0xc
the stack frame is gonna get popped so that allocation isn't gonna matter anyways
nothing you do inside a function is going to allocate new stack space unless you use stackalloc
please don't do THAT in a loop
just calling a function allocates stackspace
unless it's TCO'd
well, that's not inside that function at that point, that's a new function lol
i mean. yeah, so it's in a function
you know what i mean though lol
not really, no
the normal stack allocation is using functions and locals
so.. that's what we're talking about
if you call a function a million times in a loop you won't run out of stack space because it uses a fixed amount and pops the stack when it returns, that's what i mean
sure, but this is recursive
you can run out of stack space if the "loop" you have is recursion without TCO
that's what a stack overflow is
why cant i access the dict?
you can. read the error
the error isn't about the dict
it's about what you're doing with the result
You can
You are, in fact
it's just that an int is not a bool
next key is a vector2int though?
Yes. And presumably so is distanceValue
Which is not a bool
no, distanceValue is an int
if (7) doesn't make sense
and the dict is a vector2int type
sure
read the actual error
if wants a bool
you're giving it something that isn't a bool
Ah, right, my bad. Both are equally not a boolean so the distinction doesn't much matter
Yea this sounds like a miss understanding
From the looks of it, probably what you want is TryGetValue
That returns a bool — if the key/value pair exists, returns true and outs the value. Otherwise returns false and outs a default value
But then you don’t need ContainsKey
So you could also refactor it to be more concise
Or if distanceValue is indeed meant to be a bool maybe give it a clearer name of what it is supposed to indicate
“isOccupied” or whatever
Which is better, Resharper or whole tomato Visual Assist?
it means that it isnt touching the thing, was an old scripts variable i reused but didnt properly rename
fun fact, most ides have a "rename symbol" feature
is there an alternative to Physics.checkSphere/box to find out if a specific point is colliding? i cant seem to get the check system to work for me at all (i might be using it wrong, rn i cant even get it to detect anything which is why im not checking for layers)
F2 for vscode, not sure if other ides use the same keybind, but you can probably find it in the right click menu
ill check that out, thanks
if a specific point is colliding
what do you mean by that?
basically im checking if ground (part of a tile map with collider) is in the same position that i am checking (nextPos)
atleast thats the goal
damn i was gonna suggest IsTouching but that's 2d only...
oh
You should be able to check if the shape contains a point iirc 🤔
why are you using Physics then?
that's for 3d lol
you wouldn't use a sphere or a box in 2d
couldnt find any alternatives 😭
you'd use a circle or a square, provided by Physics2D
i didnt see an equivelent with 2d but i may be blind
actually 2d also calls it a box, nvm on that last point lmao
Physics isn't going to work with 2d stuff
unity has 2 physics systems, one in 3d, one in 2d
they don't interact
the stuff without any suffix are 3d, the 2d stuff are marked as such
seems like i would need a collider on the origin object for this which isnt possible in this case, let me try the overlapcircle rq
layerMask are weird..
there we go! tysm
Hello, I have a question.
In Unity, an Animator is instanced. How do I make so that Animator is not instanced (having exactly the same variables)? I have exactly 2 same rigs, and I want them to play the same animation, but I don't want to put script inside the second rig.
In Unreal Engine, the AnimBP is shared in the character blueprint (if we have 2 rigs using same AnimBP, the variables would share).
private void OnGUI()
{
GUI.Label(new Rect(10, 10, 200, 30), $"Total Pool Size: {bulletPool.CountAll}");
GUI.Label(new Rect(10, 30, 200, 30), $"Active Objects: {bulletPool.CountActive}");
}```
I'm having a really weird issue with the object pool API, so put a simple function in there
For some reason the list of Active Objects is a negative number????
And the pool never gets larger than 2?
I've set the default capacity to 50 and max size to 200 but only one object is ever created in the pool and after a while it just destroys itself instead of disabling
that sounds like you have some other code destroying it
The COuntaCtive issue might come from destroying objects rather than returning them to the pool
The only Destroy call is when the ObjectPool should be destroying it... i'm pretty sure they're not being destroyed anywhere else
Really weird things are happening in general with this
Only one bullet ever shows up in the hierarchy despite the fact that I know there's multiple of them
Yeah there's no code here destroying the objects.
why doesn't the API just instantiate the pool at the start?
Not filling up the object pool until the player does something like starts shooting feels completely counterintuitive to what I'm even using pooling for
why
the pool is about reusing objects
as in, not destroying them when they go away to avoid GC.
unity's object pool implementation does not prewarm, if you want that to happen either instantiate the objects and add them to the pool yourself or write your own pool that prewarms itself
prewarming is not always the right move.
it guarantees you use a lot of memory that you might not otherwise need to use.
what if you end up spawning less than what you allocated for pool
I'm just trying to figure out what the heck this thing is actually doing and why it's randomly destroying my bullets
despite the pool not being full
I honestly very much doubt it has anything to do with the pool
Do you have a particle system on the bullets perhaps
all kinds of things could be destroying your objects
Hell I'm firing a minigun here there's no way the pool is only 2 objects big
I don't have a particle system on them,
As I said before, if you want help, you really need to share more details
how are you releasing your bullets?
only the objects that reach MaxSize return to pool when not in use and get collected
(not to be confused with default size)
The shoot function's pretty big but it's just whenever mouse1 is pressed or held
how, not when
Using the Get function
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
release, not get
ohhhh
Release aka Return to Pool
On the gun script I have this part
private Bullet CreatePooledObject()
{
Bullet instance = Instantiate(bullet, attackPoint.position, Quaternion.identity);
instance.Disable += ReturnObjectToPool;
instance.gameObject.SetActive(false);
return instance;
}
private void ReturnObjectToPool(Bullet instance)
{
bulletPool.Release(instance);
}
Then on the Bullet script itself I have this
public delegate void OnDisableCallback(Bullet Instance);
public OnDisableCallback Disable;```
Then instead of calling Destroy I call Disable?.Invoke(this);
It's a solution from LlamAcademy
could you show the full script
A tool for sharing your source code with the world!
This one's the Bullet script
https://paste.mod.gg/djkdcdqiutpm/0
A tool for sharing your source code with the world!
one possibility here is you have no protection from Explode running more than once per bullet
that might lead to you trying to return the object to the pool more than once
That's true,
not necessarily the main issue but something I'm noticing
not only in OnCollisionEnter but your Update really has no protection against it. In fact if the bullet times out based on lifetime it will almost certainly call Explode several times
as many frames as you get in 0.05 seconds
I'm putting a bool in there to control that,
and at the same time I should probably be resetting the collisions counter in OnEnable
I'm trying to make cinemachine work, but the camera doesn't move with my mouse :/ I watched a few tutorial about it, and I don't see what they did that I missed
Does anyone know what i'm doing wrong here ? ^^"
I dont see anything in this setup that would make the camera move with your mouse
what kind of camera are you trying to implement here
Ah 😅 That might be the issue, all the tutorials I've seen seemed to have that behavior implemented by default ^^"
just a third person camera, I'm trying to experiement with the advanced stuff!
you should not be using Framing Transposer for that
create a FreeLook camera from the menu for a simple third person controller setup
what does the framing transposer do that I don't want compared to the other options ?
I tried doing that in the first place but I got the same issue :/ could it be because the Mouse X and Mouse Y don't have the same names depending on the configurations ? kinda like the default for moving is wasd, but only for qwerty keyboard ?
its for 2d basically
That may also be cinemachine V2 which may cause confusion compared to v3
That is v2 .. v3 has blue icons
ok i'll migrate my question there, thanks
Hi! I had some questions about scene/level loading. If I want to attach data to my scenes that define what they do/are used for like what a scriptable object does, how would I go about doing that? Are there any ways of attaching scripts to scenes so that they run whenever the scene? Is there a way to access game objects in the scene without loading it? Thanks!
Make a ScriptableObject that has all that data and the scene name
reference that
and use it to load the scene
you cannot directly reference a scene unfortunately
so whenever I call loadscene i pass in the scene from the so name?
sure or just literally put a LoadMe() function on the SO
and it can load its own defined scene
scene order in the build profile/build settings?
yeah
If you're using scene names no
ok
if you use scene index that's based on the order in the list
To make this easier there are also some third party tools which will help your workflow like https://github.com/starikcetin/Eflatun.SceneReference
what do we think about this chat 😈
this is just noise unless it's being used to resolve a naming conflict
id rather just make it myself so i understand it better lol
ty tho
ERRROR
wait wheres the error
BULLCRAP
based on these rules
it should error
bc no this.
What error
What should error
That’s not Unity code.
Not do
do;
code formatting is not something that would cause an error
also yes that
im gonna force this. in all my unity projects from now on 😈
you can force .editorconfig to cause errors for formatting
you can make it ignore, suggest, throw a warning, or throw an error
Is it possible to force a player input to use a new user
I have two player objects that are assigned to the same player, hence they use the same user
Since I'm doing something akin to split screen I'd like for one to have a new user so that they cannot use the same input device
In theory, this is what the docs are saying, but practically I create two objects with two different player input so they shouldn't use the same device, although they do
The only difference I can see is that one doesn't have that user field
Also weirdly enough there it says it's linked with the gamepad, but the gamepad doesn't work, rather the keyboard does, which is supposed to be only linked with user 0 (in another unity player)

