#archived-code-general
1 messages ยท Page 267 of 1
Nope, Nothing happens. The only thing is if I double click the log, it opens the script. Otherwise nothing is really highlighted
shall i send a video
Did you put the comma and this after the string in the log?
Pause the editor during runtime and click the log.
I'm assuming you're instantiating objects during runtime and that they do not exist outside of playing the application.
tried that, doesnt highlight anything except the message itself
yes
use /* to start commenting out script with error, and */ to end comment.
this way the editor can compile and you can configure your IDE properly .
Also this belongs in #๐ปโcode-beginner as you seem to be missing c# fundamenetals
most of them, yes. Especially the road/lanes
If the object hasn't been destroyed, it should be highlighted yellow in the scene when the log is selected.
Or a prefab would be highlighted yellow if the script was called from a prefab.
If I talk about the pickup object. When u pick it up, I instantly destroy it after calling LaneIncrease()
So you're referring to two different objects then.
I have the same script attached to a prefab as well, and also to a gameObject in the heirarchy
I'm going to assume that your bool is from two different objects and that the one you're setting to true isn't the one being checked.
Otherwise, you've set it back to false sometime before checking the value.
there are 5-6 objects using my same script. Out of which some are just Road/lanes itself. The Other one is the PickupObject, and the Spawner GameObject in the heirarchy
how do I check static flags of a gameobject? There seems to be only this bool, but there are multiple flags, I expected an enum.
What static flag?
They likely aren't using the same script.
nevermind, I realized they were called static editor flags and finally hit the keyword in google to find what I need
Note that they're editor-only
Clicking the log should have highlighted the objects who the script belongs to in the scene. For example:cs public class WhoAmI : MonoBehaviour { // Start is called before the first frame update void Start() { Debug.Log($"Click this to have {name} highlighted yellow", this); } }
i see... But somehow it doesnt happen in my project
The objects that had the logs are likely no longer in the scene/editor (they've been destroyed)
But ultimately, I was trying to figure out if the bool you're checking is the same as the one you've set to true.
okay, but what about the latest Lane that has been instantiated. It has the same scripts. Why dont they get highlighted
And they aren't because both components aren't in the scene anymore.
Scripts have instances. These instances aren't referring to the same script.
so what should I approach now
If you create 3 lanes, each lane will have their own component scripts that are attached to themselves.
yes
Have someone else manage the data ๐คทโโ๏ธ
When you instantiate them, you can provide them the reference to that other objectcs var lane = Instantiate(...); lane.manager = manager;``````cs if(manager.laneCount > 1) { ... }``````cs if(manager.laneIsMoving) { ... }They would all be referring to the manager's data (assuming lane count and lane is moving should be managed as one instance only)
I was referring to some other object who'd maintain the data.
pun was intended
lemme go through it
Here is how I reference it in the PickupManager script:
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (gameObject.tag == "LanePlus")
{
if (lane.LaneCount < 6)
{
lane.LaneIncrease();
Destroy(gameObject);
}
else
{
Debug.Log("Lane Count Exceeded");
Destroy(gameObject);
return;
}
}
In the beginning:
public LaneManager lane;
void Start()
{
lane = GetComponent<LaneManager>();
}
Post inline code using backticks (```) before and after the lines of code or use one of the links below (copy/paste !code to site, save and then post the URL here)
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
alr
No
Be mindful, if someone requests your code as text, don't send a screenshot!
okay got it
Dalphat explained how to do it, and the bot did too. Why screenshot? Just interested in how that decision was made
imma give an explanation but im burnt out by figuring out whats wrong with my code. So lets not deviate alr
imma send u inline
public class PickupManager : MonoBehaviour
{
public LaneManager lane;
void Start()
{
lane = GetComponent<LaneManager>();
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (gameObject.tag == "LanePlus")
{
if (lane.LaneCount < 6)
{
lane.LaneIncrease();
Destroy(gameObject);
}
else
{
Debug.Log("Lane Count Exceeded");
Destroy(gameObject);
return;
}
}
if (gameObject.tag == "LaneMinus")
{
if (lane.LaneCount > 2)
{
lane.LaneDecrease();
Destroy(gameObject);
}
else
{
Debug.Log("Lane Count Minimum");
Destroy(gameObject);
return;
}
}
}
}
}
So this object has the Lane Manager on it but you're destroying this object on trigger.
I'm hanging during build on this. how do you check what it was doing when it stopped?
Yes the pickup item after picking it up gets destroyed
This implies that every object has their own "manager" and that none of these "manager"s are likely referring to each other.
might be
So if object A sets his managers bool to true and object B asks his manager if they've set the bool to true, the answer would be no (false) because they've both got different managers.
makes sense
GetComponent implies that this manager is on this object - the object that has been destroyed.
yes
Consider having the manager elsewhere and assigning this object's reference to the manager when it's instantiatedcs var consumable = Instantiate(...) consumable.manager = manager;
Like attaching it to a gameObject in hierarchy right?
Put the manager on the object spawning these consumable/powerups
When the objects are spawned, tell the object who the manager is.
how do i tell them that which reference is the actual manager
Is on the object being destroyed according to this #archived-code-general message
It shouldn't be on the object that's destroyed. And they're instances of a prefab, not the actual prefab.
i see
When you create a new instance of the prefab, you'd tell that instance who the manager is #archived-code-general message
they are randomly instantiated. So should I create a reference of Pickup Item on the LaneManager script itself (the one on the Spawner GameObject in the Hierarchy)?
Im sry I didnt get you here. Can you elaborate the second line?
So.. you've got an object in the scene with the lane manager script. It would create lanes whenever necessary. If you need data shared between these lanes, you'd tell these lanes when you create them.
yeah
In your case, I'm assuming you're wanting to share the bool between the lanes.
Yeah, so have the component/script that's holding the bool not be on them but be shared to them.
i understood what youre trying to say. But I will get more clear conceptually if you tell how do I share them without getting confused or redundant?
My coding is very redundant
I've given a lot of examples already. You'd simply pass the reference to the object after instantiating it.
reference should be included in the Object's script or the LaneManager
I think you've already got a lane variable in pickup manager.
You just need to assign the manager to that when you spawn the object with the pickup manager component.
Unfortunately, it's a reference to it's own unique lane manager that you've assigned in Start
oh
so instead of putting the reference in the start
i should reference it the line where it instantiates?
The component isn't the same component that all the other pickup managers have.
I see
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have another script
PickupSpawner
Which only instantiates them
doesnt manage collision
if (colliders.Length == 0)
{
int randomObject = Random.Range(0, pickupPrefab.Length);
var pickup = Instantiate(pickupPrefab[randomObject], spawnPosition, Quaternion.identity);
pickup.lane = laneComponentThatShouldBeOnThisObjectOrAnother;
}```
Where you'd remove the lane assignment in the Start method of the pickup manager (it's not really a manager of all pickups but just one single pickup instance)
Where laneComponentThatShouldBeOnThisObjectOrAnother would be a component on this object or some other object that persists.
That would be shared by reference to each and every instantiated new object with the pickup component.
You'd only be able to access pickupPrefab's lane field if you've referenced the game object by it's component.cs public PickupManager[] pickupPrefab;
The reference laneComponentThatShouldBeOnThisObjectOrAnother would be either assigned through the inspector, get component or given to it like how it's passing the data to the instantiated objects - referencing through the inspector is preferred.
whats the lane field
Is it technically possible to run .NET 8 code by compiling it into a NativeAOT library and then P/Invoke into the library?
That's a new level of perversion.๐
If it's a native library, what's the point? It's probably gonna get compiled into the same thing anyway
Lmao, the point would be to use newer APIs that Unity doesn't have access to yet
But it's all just syntactic sugar. Are you going to write the whole project as a library or something?
This is all just theoretical. I think it could possibly have some use cases if you desperately needed newer APIs for a certain task. Definitely would not use everywhere
And it's not just syntactic sugar right? .NET 8 code will run faster, since the .NET team has been heavily focused on performance the past several years
The only downside I see, is that it has to be compiled for every architecture and most likely won't work on every platform
I think it should work on Windows though
Unless it runs as IL(which contradicts the definition of a native library), there's no point to the optimizations.
Is that because of the overhead of calling into unmanaged code?
Is there a way I can make a variable but allow it to be modified by sources outside of its class?
make it public
i dont want the class its in to be able to modify it
that is not a variable it's a property
That too, but it's simply gonna compile to C++. All of the dot net optimizations are implying that the code runs in dotnet. If you compile it into a native library, it's not gonna run in dotnet runtime.
If you mean not allow, then make it private set instead of prevent set
no i mean i want it to be able to be modified outside of the class but not inside if possible
basically I have an inventory class that holds the information about it but these classes are in two different assemblies
no, a class will always have read/write access to it's variables
The best you can do is readonly or init
ok
In the first place, that intention doesn't make sense.
Init doesn't work in Unity afaik, unless the newer version supports it
.NET 6+ only feature, not .NET Standard
I have a class called Inventory, the other on is called GunController. Inventory holds the count of totalammo. GunController needs this information but both the classes are seperate
I want to keep them seperate, on seperate assemblies
Are you sure, I'm pretty sure all of the parts of the dotnet runtime the library uses will get compiled natively into the dll.
i need help making a mesh for a procedural generation map i am making
my brain melts
You can make it work, you just have to define the IsExternalInit class yourself (I don't remember the minimum version this works in, but it's at least like 2021 maybe 2020)
That's not gonna be a "native" library then
Sure, but then you might aswell get PolySharp to handle polyfills automatically
Yeah sure that works too
Also, I don't think it's gonna work in this case, as the code would be running in the runtime that unity supports.
Not the code inside the NativeAOT compiled dll. It would be running it's own version of the natively compiled .NET 8 runtime
It won't compile the whole runtime, it trims what it does not use
It even will have its own garbage collector
To Unity, it has no idea it is even calling "C# code"
Your field that would increase count and whatnot. You wouldn't want it to be destroyed with the spawned object so have it on a different object and just pass/assign a reference to it when you spawn the objects that can be destroyed.
Hmm... In this case that might work, but I wonder if the overhead would be worth it.
understood, I will try this
Yeah that's what I'm wondering too, for certain use cases I think it could.
Unity calls into native code all over the engine, though this is slightly different.
Also, as I said previous it does actually impose many limitations. It doesn't create a runtime environment, it compiles to native code.
Native AOT apps have the following limitations:
No dynamic loading, for example, Assembly.LoadFile.
No run-time code generation, for example, System.Reflection.Emit.
No C++/CLI.
Windows: No built-in COM.
Requires trimming, which has limitations.
Implies compilation into a single file, which has known incompatibilities.
Apps include required runtime libraries (just like self-contained apps, increasing their size as compared to framework-dependent apps).
System.Linq.Expressions always use their interpreted form, which is slower than run-time generated compiled code.
Not all the runtime libraries are fully annotated to be Native AOT compatible. That is, some warnings in the runtime libraries aren't actionable by end developers.
That should work, but you can't prevent a class from modifying it's own non immutable fields.
What I would do is have a public TakeAmmo method in the Inventory class that the GunController can call into.
This way the Inventory class is the only one that can modify the ammo count field directly.
This is the kicker
'Windows: No built-in COM.'
The thing thats connecting the two is a class called PlayerMaster. I'm not sure how to implement TakeAmmo without calling every frame. do you mean RequestAmmoCount.Invoke()?
This is what I have atm
_inventory.ModifyInventory(ItemType.Ammo, interactable.GetValue());
_gunHandler.TotalAmmo = _inventory.Ammo;
break;```
I literally just mean add a method to Inventory
public int TakeAmmo()
{
}
class ??
Sorry lmao
How do I connect the two though? Is it something like..
_gunHandler.OnTakeAmmo += () => _inventory.TakeAmmo()
If the event OnTakAmmo of the gunhandler is When it needs to request ammo then that would work.
It's probably better design to just inject the Inventory class into the GunHandler so it can call into it when it needs
Is that possible without them knowing each other, I want to keep the assemblies seperate
Where are the types defined? If they're each in their own assembly, one of them would need to reference the other. Or even both.
That would be in the PlayerMaster class
You also don't need the lambda that wraps the method. This works:
_gunHandler.OnTakeAmmo += _inventory.TakeAmmo;
And what assembly is it in?
PlayerMaster
So a third assembly?
Just curious, but what are you trying to achieve by splitting your code base into so many assemblies?
The thing is it's not a one way variable. When the gunHandler reloads it needs to modify the AmmoCount too
I believe its abstraction but also it helps with compile times
You could have an IInventory interface in it's own assembly that both assemblies reference, then inject the interface into the gun handler
Regarding abstraction, you can keep it abstract in one assembly. As for the compile time, I wonder if it's worth the additional time you spend on development and adjustment, like now.
Yeah unless your project starts to get large, splitting into assemblies isn't really worth it
Ive noticed a big difference so far in compile times and overall I like it because I know where everything is, before I would edit something and i would have to adjust 3 other things
I see
I think what I need to do is actually create a struct containing the data, and as the values get modified
Both sides know the value
Maybe a class
No events will be needed this way
You'd need some commonality between the assemblies. If each define their own data structure, I feel like they're gonna collide.
The concern is that if I go with the common class PlayerStats
theres alot of info on there that GunHandler doesnt need such as Health,Movespeed etc
should I be concerned about that?
Its a cheap way to sharea variable without having to set up events though
Maybe break it down into several classes
Like GunInfo
Should I make it a struct?
You could, just be aware of pitfalls with mutable structs
Probably makes more sense to be a class tbh
ill give it a shot thanks
Sorry I missed this message earlier. Yes it does impose many limitations, but it could be beneficial for use cases inside of those limitations.
I could be wrong with how I was wording it, but what I meant is this:
Let's say there have been substantial improvements with http requests and the List class since .NET Standard 2.1
And I have a method that makes a HTTP request and processes the data. If I move that code into a .NET 8 NativeAOT library, then when Unity calls the method natively, it benefits from all the improvements made to http requests and the List class since .NET Standard 2.1.
Hello, in NavMesh.CalculatePath() and NavMesh.SamplePosition() there are area bitmask parameter. What is that?
The example use NavMesh.AllAreas but what does that mean? I can't find info about this.
I'm using NavMeshSurface to generate my navmesh, is there a way to use specific NavMeshSurface?
Also I don't know what's up with the docs with that page, some versions have it, some don't
Like its missing from 2022.3 docs, but is in 2023.1 docs
And then missing again for 2023.2 and after
Ah thank you. looks like it's not what I think it is.
Heya, so I'm trying to implement dynamic LOD for GPU instanciated objects (grass blades). I opened my original lod0 grass blade and just removed a few vertices for each of them in blender (Note by all means I am useless at blender). I imported them and set em all up but I'm having this weird issue during my shader animation. Bit counter intuitive but left to right is lod5 -> lod0. Thanks very much all!
How does your shader animation work? Does it use vertex position or vertex color or something like that?
Hi all. I'm implementing a custom render pass, drawing objects to a seperate render texture using an orthographic box around the camera, however, there seems to be some issues with the ortho matrix where it seems the near plane is set at a distance of zero from the camera, rather than extending backwards like I want. I'm sure unity allows a negative near plane for ortho matrices, but for some reason it seems to either be clamped at zero for me. Heres a code snippet where the view/projection mats are created alongside the culling if that helps: ```//Create view and projection matricies
float size = voxelSceneSize * 0.5f;
Matrix4x4 viewScene = Matrix4x4.Translate(camData.camera.transform.position);
Matrix4x4 projectionScene = Matrix4x4.Ortho(-size, size, -size, size, -size, size);
ScriptableCullingParameters cullParams;
if (camData.camera.TryGetCullingParameters(out cullParams))
{
cullParams.cullingMatrix = projectionScene * viewScene;
cullParams.isOrthographic = true;
cullParams.cullingOptions = CullingOptions.None;
//Set culling planes
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cullParams.cullingMatrix);
for (int i = 0; i < 6; i++)
{
cullParams.SetCullingPlane(i, planes[i]);
}
CullingResults cullResults = context.Cull(ref cullParams);```
Additionally, heres a short clip. The green box around the camera shows the desired ortho box, but in the output texture its clear that the cubes are clipping right at the camera rather than the back of the box:
I'm setting the near plane to -size in: Matrix4x4.Ortho(-size, size, -size, size, -size, size) but it behaves as if its set to zero
Thanks in advance
Calculates an offset based on noise, then applies a UV-G product so the top moves more than the bottom
So you're using UVs to determine how far along the blade each vertex is? Then the UVs probably got messed up when you removed vertices.
Very good point! I'll check that ty
Only thing is I didn't change the height of it so using the G channel should be fine tho no?
How can I draw a rectangle from a point and normal?
As you can see in the image, the following code doesn't create the rectangle with the correct orientation ๐ฆ
Quaternion quaternion = Quaternion.LookRotation(new Vector3(0.0f, 0.0f, 1.0f), normal);
Vector3 right = quaternion * new Vector3(size, 0.0f, 0.0f);
Vector3 forward = quaternion * new Vector3(0.0f, 0.0f, size);
Vector3 a = right * 0.5f;
Vector3 b = forward * 0.5f;
Vector3 upRight = point + a + b;
Vector3 upLeft = point - a + b;
Vector3 downLeft = point - a - b;
Vector3 downRight = point + a - b;
WalkableTexture.Release();
WalkableTexture.width = _worldGrid.GridSize.x;
WalkableTexture.height = _worldGrid.GridSize.y;
WalkableTexture.Create();
Texture2D tex = new(_worldGrid.GridSize.x, _worldGrid.GridSize.y);
foreach (var tile in _worldGrid.nodes)
{
tex.SetPixel(tile.gridPosition.x, tile.gridPosition.y, tile.Walkable ? Color.black : Color.white);
}
Graphics.Blit(tex, WalkableTexture);
Hey, so I'm doing something like this
i basically want to make a black/white texutre that represents walkable tiles
but for some reason, generated RenderTexture looks like this:
tex.Apply() ????????
thanks !!!!!!!!!!
I believe viewScene should be inverse.
Where does the G channel come from? A texture sample? That's still based on UVs.
LookRotation will always prioritize the forward vector, which is fixed in your case. If you want to point the up vector a certain direction, you should use Quaternion.FromToRotation(Vector3.up, normal) instead.
Yeah I saw that immediately after posting and fixed it. The clipping issue still remains tho
Oh, thanks
I am trying to get the tiles in the tileset. How do I use Resources.Load() to do this?
This returns null
This is my code cs Sprite loadedSprite = Resources.Load($"{spritesheetPath}_{i}") as Sprite;
Put them in a Resources folder
The "Sprites" folder?
yes, It might help if you went and read the Resources.Load docs
Sorry 
Hey, I'm doing a 3D golf game, and I'm trying to recreate the curved ball effect when hit by the club. I pretty much have everything set up, I hit the ball, the ball flies, spins, and curves based on the spin strength. Nice. What I am missing is how to detect if the ball was hit inside-out or outside-in, so I know if it should spin clockwise or counter-clockwise.
I need to check the angle between what, direction of the club movement, and...? The ball is stationary so I can't use its position
and I can stand anywhere around the ball, even shoot backwards
Hello everyone, I have a code that when I collide with player that is driver and he drives a car, the other player will be transported on top of that car and he will ride on it and when he wants to get down, he clicks "I" and get teleported down but for some reason when I press "I" it doesnt do anything. Can anyone help? This is happening on line 64-69. This is script: https://hastebin.com/share/mikayugiga.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
private void Update(){
// Check if the player is on the car
if (isOnCar){
// Disable movement and rotation controls while on the car
return;
}
btw i dont use early return, usually goto the end (if the language supports goto) to prevent missing computation.
private void Update(){
// Check if the player is on the car
if (isOnCar){
// Disable movement and rotation controls while on the car
return;
}
some codes
if (isHolding && Input.GetKeyDown(KeyCode.I)){
Debug.Log("Down");
// If "I" key is pressed while holding, transform the player down
TransformPlayerDown();
}
}
The GetKeyDown() only happens on the first frame the key is pressed.
I think you just want GetKey() instead
your code even not running at all
I changed it, works now. Also does anyone know why my car when he is driving or player when is walking and collides with something like a tree or house he can get trought it even tho everything has box colliders correctly set
rigidbodies?
yes car and player and tree have rigidbodies
show inspector of objects
All your movement and rotation is done via transform which does not respect physics. Switch to Rigidbody only
yep, if you want physics collisions
moving transform is a hard teleport. It will go there if you tell it to, even if that puts a box in a wall.
and the box will only realize it needs to move during physics simulation step, which can produce strange results.
if I load all SceneAssets (only them, not Scene object themselves) into some sort of LevelManager at initialization stage of the game and after that I'll load them as Scene object by some key or so (to avoid strings or ints to load them) - is it bad idea to do it that way?
I'm loading them by Addressables, if it matters
I changed the script to using rigidbody and froze rotation on Z axis but when I collide with tree it still rotates me and I start floating
nice
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi guys, I'd like to open the shop, which I made into a function, but it doesn't open, my code: https://hatebin.com/wyzuyoysfw
is this script on the shopui gameobject?
yes sir
Update does not run on deactivated objects
you could make an empty parent object for shopui and put the script on that
thank you!
have a great day!
How can I prevent my npc character controller from moving on top of my player charactercontroller, when the player stands in the npc's way? (I will eventually add specific movement reacting to the player, but I feel like there's something wrong with the capsules, I have the npcs randomly roaming around and they will hop on top of stuff occasionally (even though their step offset is set to 0.1)
center, radius, height are (2.3, 2.3, 2.4) and my player controller is (0.8, 0.3, 1.6)
( to allow them moving down slopes I the np'c move with : _controller.Move(Time.deltaTime * (direction + 3f*Vector3.down)) but even with this additional downward move vector they will pop on top of my player if I "harass them", I'd like to make it impossible somehow)
(without making my player capsule taller)
Is there a way to get an object's normal without raycast
what do you mean by "an object's normal"? (a normal is perpendicular to a shape at a given point, a model will have many normals, when you hit it with a ray you get a normal at the intersection point)
which normal?
Hello, does anybody know if there is a way to make a function execute in edit mode? I've got a custom button in the inspector to change the color of a light source in game, while it works and changes the color in the inspector then when the game starts the color will be changed I would like this to happen in the inspector, I also have this working by adding [ExecuteInEditMode] above the class name but this means I have to have code in update which I would rather this only happens once by using the custom button that calls the function, that was a lot of yapping for a single question my bad
Hi, I pressed F and it won't activate, my full code: https://hatebin.com/yhqcejgdqt
Either write a custom inspector or use something like NaughtyAttributes: https://dbrizov.github.io/na-docs/attributes/drawer_attributes/button.html
obviously not. true + false = false
you are both activating and immediately deactivating in the same frame
oh, how do I fix it? I'm sorry but I am a beginner
Something like:
if (Input.GetKeyDown(KeyCode.F))
{
shopui.SetActive(!shopui.activeSelf);
}
``` would be expected
TY!!!!
yo that looks quite useful, thanks!
It doesn't work
show your code and what happened
that's the same code as before
You need to change the code to something like I shared above
You left part of your old code in
delete this cs if (Input.GetKeyDown(KeyCode.F)) { shopui.SetActive(true); }
you only need the snippet I shared
NaughtyAttributes is great.
we should have more custom editor tools that work like NaughtyAttributes, where you just apply an attribute to modify the editor.
Sorry, I meant a faceโs normal. Aaand by you asking that question I understand why you need to hit it with a raycast. Ty
well if you already know which face - you can deduce the normal from three points on the face (i.e. the triangle)
otherwise, the raycast identifies the triangle in the first place and therefore the normal
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Anyway this code should prevent what you said - so something else is going wrong.
then why DDOL?
My guess is you have "Play On Awake" enabled on the audio source
Already
What does "Already" mean?
i try enabled the Play On Awake" the audio source and i try disabled but doesn't work
It should be disabled.
Anyway - you need to debug your code
I think your problem has nothing to do with this code you shared
How can I stop a certain light to cast on a certain sprite renderer with Light 2D
The light has a culling mask
Also this isn't a code question. #archived-lighting
thanks
In mobile (specifically android), we have a landscape app and the default behavior of Unity when a user taps an input field is to open a tiny floating keyboard instead of the usual, large "docked" one on the bottom of screen. There is a button to change style right on the small floating keyboard to change it back, but users are complaining. Is there some easy way in Unity to just tell it to open the standard docked version of the keyboard?
anyone have an idea as to why transform.forward isnt making the bullet go forward when a parent has negative y rot?
you'd have to show the code
and which objects are referenced by it
@warm cobalt ^^^
playerCam.transform.forward + direction < this "direction" variable is going to alter the direction from camera forward
is just 2 random floats basically speaking so it's not really relevant
Why do you think it's not relevant? Seems very relevant
Also... you're even incorporating the current facing direction of... some object?
transform.forward + transform.right * randomBloom.x + transform.up * randomBloom.y;
this is ... very strange to say the least
Btw instead of adding vectors to create random spread, the better way is to rotate the vector
it's more controllable/predictable/understandable/effective
the reason we added is because i wanted the spread to be the same regardless of distance for this game
yeah its out of the norm
sounds like a perfect job for rotating the vector
Or - i guess you mean the spread pattern on whatever you hit?
yeah
Either way this calculation seems really off:
return transform.forward + transform.right * randomBloom.x + transform.up * randomBloom.y;
specifically - adding transform.forward .. and this isn't even the camera object right?
thats what i said yesterday
Your SpawnLine function also seems off
nevermind, fixed it.
last time when we had an issue similar to this we replaced transform.forward with playercam.transform.forward and it did nothing
so we just assumed to keep it that way.
but that was the fix in this case
well, thats a question for him. i dont really do the scripting. i do visuals and design
When you call it you're passing in... I think a direciton vector?
SpawnLine(origin, playerCam.transform.forward + direction);
But then inside you're treating that like a position:
line.SetPosition(1, hit);
I think this SpawnLine(origin, playerCam.transform.forward + direction); should be SpawnLine(origin, origin + playerCam.transform.forward + direction) maybe?
the script is kind of in need of a rewrite with how much code isn't very well thought through
well thanks for the insight @leaden ice
this looks good asf??? whats the name and where can I play it
reminds me of pixel gun 3d
wishlist in bio, free of charge :)
ah say no more
i have an int for coins. When i use coins -= 4 nothing happens. i want to lose coins.
show !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
all of the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
coins =- 4;
you said -=
i tried both
i don t know why but when i have the coins negative. For example -43 it works.
now it works but when i reach 4 coins it just reamains 4
ok
hello guys, i've got small problem, i donwnloaded animation from mixamo, and problem is that when anim is played avatar's position is changed, i want to play anim in a way that avatar's position stays the same, i turned off Root Motion, but still same...
you do realize this code makes no sense
public void skillselect1(){
skillselected1 = true;
print("1skill");
if(skillselected1 == true){
skillselected2 = false;
print("2skillfalse");
}
}
public void skillselect2(){
skillselected2 = true;
print("2skill");
if(skillselected2 == true){
skillselected1 = false;
print("1skillfalse");
}
}
thanks i got it anyyways
is ok if i did smh like this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
no
Don't do variable1 variable2 ever. Make a list or something. Make a struct or class that contains the necessary information to buy it. Abstract it
why is that?
public void Buy(){
if(skillselected1 || skillselected2)
if (coins >= 4){
coins -= 4;
skillselected1 = false;
print("firstskill");
}else{
print("notenoughcoins");
}
}
your logic is incorrect
format your code properly to make it more readable
why so many if statements ๐
isn t it the same thing but && transformed in an if
No
that is actially 2 less than he had
oh ok
look at his code, think what happens if skillselected1 is false
meaning of && is "and"
Correct
You can google that if you needed to know. Simple things like that should be googled before asking here. But no worries
i know that
the logic is now different
ok i got it thanks
see updated code above
anyone know, how can i fix it?
and where is the code question?
I have some npc's using CharacterController and calling controller.Move(some_directionspeeddeltaTime); 1) How do I stop my npc's from climbing on top of each other if they're bunched up against each other? They have 0.1 step offset and still walk over each other. 2) why is my player character controller able to push them? (and when I do push them they clip over each other)? (This one is super weird as I have a different npc setup in almost exact same way (diffrent logic to determine the move direction) and my player character controller CAN't push that one. Would appreciate any pointers on what to look at or how to debug this.
Without seeing the code it's hard to say. One tip is that you need to make sure CC.Move is only being called ONCE per frame.
the npc that works as expected has ragdoll rigidbodies, set to kinematic as long as it's animating, I tried adding a sphere collider and a kinematic rigidbody to the other ones, but still they behave differently
Also multiple CCs can act weird because they move at different times and they probably don't see each other's new positions due to how the physics engine updates.
I have a different npc setup in almost exact same way
Ragdoll Rigidbodies sounds like a very different way than a CC.
When I want that npc to ragdoll I disable it's animator and unset kinematic on it's rigidbodies and it ragdolls. that part seems to work correctly.
void Update() {
var targetRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 40f * Time.deltaTime);
_speed = Mathf.Lerp(_speed, speed, 1f - _dirchange);
_animator.SetFloat(_animIDSpeed, _speed);
_animator.SetFloat(_animIDMotionSpeed, _speed);
Vector3 move = transform.forward * _speed + Vector3.down * 3f;
_controller.Move(move * Time.deltaTime);
if (_dirchange >= 0) {
_dirchange -= Time.deltaTime;
} else {
_dirchange = 1f;
speed = Random.Range(0.2f, 0.2f);
}
}
Here's the one that works as expected (doesn't allow itself to be pushed):
void Update() {
direction = _stateController.player.transform.position - transform.position;
direction.y = 0;
direction.Normalize();
// turn towards
Quaternion towardsDirection = Quaternion.LookRotation(direction, Vector3.up);
float animSpeed, speed;
float dot = Vector3.Dot(transform.forward, direction);
if (dot < 0.5f) {
speed = 0.15f * Time.deltaTime;
animSpeed = 0.2f * (dot +1f)/2f;
} else {
speed = dot * 2f * Time.deltaTime;
animSpeed = ((dot < 0.8f)? 1f : 1.3f) * dot;
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, towardsDirection, Mathf.Max(40f, 20f * 3f - dot) * Time.deltaTime);
_animator.SetFloat(_animIDSpeed, animSpeed);
_controller.Move(transform.forward * speed + Vector3.down * 3f * Time.deltaTime);
save for some creazy animation speed manipulation on turning which I should get rid of or cleanup the movement itself is almost the same. So it must be something with the setup of the character controllers?
Hi, so I am trying to implement an animation of something like this: https://www.youtube.com/watch?v=LXJUYumwh-k. I am working on the color part when the rotating object comes in contact with the stationary object. I basically implemented a collider for each tooth so to speak and I am not sure how to go about it after taht. Is there a way where you change the color of a gameobject based on the percentage of alignment between the two objects?
The changing magnetic field due to the rotation of the rotor in a switched reluctance motor (SRM). This animation was created using MagNet, the electromagnetic simulation software from Infolytica Corp. Read more at http://www.infolytica.com/en/applications/ex0147/.
the closes thing will probably Vector3.Dot() https://docs.unity3d.com/ScriptReference/Vector3.Dot.html
how are you defining alignment?
if it's based on distance, then you'll want to measure the distance between two points (probably the position of yourself and of the other collider) and adjust your color based on that
I am using ontriggerstay but it is not working great because it only fixes on one color
you're going to have to give more details on that because "it only fixes on one color" is not meaningful to anyone
any idea why Physics.Raycast still detects trigger collision box even tho layer mask is set to collision-less?
You'd have to show your code, how you configured the mask, and the layer that the given collider is on.
Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, reachDistance, mask)```
mask = 1 << 8;
mask = ~mask;```
how you configured the mask
this mask will hit ALL layers except layer 8
including the "Ignore Raycast" layer
yes
So what's the problem?
ignore raycast is layer 8
yes
show your layers?
Pretty sure it's like layer 3
Anyway - there's no need to make a custom mask to specifically avoid the Ignore Raycast layer
the default layermask already does that
so you can simply omit the layermask parameter
oh you're right
its different id than 8
but it should ignore it by default when set?
mask = 1 << 8;
mask |= 1 << 2;
mask = ~mask;```
now it works thanks for your help
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use link โซ
Try mathf.abs(vector3.dot(obj1.transform.forward, obj2.transform.forward)) the closer to 1 the more "aligned " the objects are. Let me know if this is close to what you want
So for example this is the code for one of the teeth of the parts https://paste.ofcode.org/Fa5TwReCzyvBjyQJfbh7Gk. The image attached shows the circled gameobject is called north-west and the rectangle object is "other" gameobject. This is the snippet of the code but the same idea can be applied for the other gameobjects. I have an array of colors that TransitionNW goes through in 4 seconds and then it loops through once it is done going through all the colors.
yeah I think I will try that and let you know
let me know if something doesn't make sense
Flipping the boolean in on stay seems weird. Triggeronstay will be called on every fixed update until the object leaves the trigger.
someone can help me to do a system of upgrade with cards? I will post a screenshot to explain better
I just want some guide to where to find tutorials about it
i dont find any
That's a very complicated system that is going to have to tie closely into how your actual combat gameplay and saving/serialization systems work
it's not really something you would be able to use a tutorial directly for
more like - learn the concepts and roll your own.
hmm I see
thanks
do u have some tips to get there?
some resources to learn or something
I liked a lot that system and i wish so much to introduce in my games
its so fun
Is this a bug?
[System.Flags]
public enum CellEffect
{
Open = 0,
All = ~0,
AllExceptBlocked = ~0 ^ 1,
Blocked = 1,
Mud = 2,
Storm = 1 << 2,
Burning = 1 << 3,
}
Why do I have this weird block instead of a line? it's breaking my scripts, how can I fix it?
pres Insert on keyboard
thanks
the zombies and sheep use CharacterController with a single call to Move() in their Update() and yet they behave very differently. The zombies seem more "planted", while the sheep very easily bump into the air. Is this something that should work with character controllers or should I ditch the character controller and use rigidbody capsules for the npc's/critters/enemies? I just don't know what I'm missing with the sheep setup that's causing them to behave so differently.
are the zombies navmesh agents?
no, both sheep and zombies just come up with a direction, rotate towards it and then _controller.Move(timeDelta*(speed*direction + Vector3.down))
The only 2 diffrences are: the zombies have a ragdoll on them with all rigidbodies set to kinematic, but I don't think that's it as I added a box+kinematic rb to some of the sheep armatures and it made no difference. The other one is I tried to fit the character collider capsule around the sheep which resulted to them being "ball shaped" which kind of explains why they move like balls a bit?
why not use navmesh agentss
giving them skinny capsules like the zombies have made no difference.
I'm thinking of doing that down the road if/when I learn how to use them. Does having a navmesh agent replace the character controller though? I'll still need something on them to collide with?
Plus my issue here is with the sheep: and the sheep can't be navmesh agents cause I want them to use flocking behaviour (ok actually they could be navmesh agents still).
but what would that really solve? maybe I wouldn't have to add the downward vector to their move code?
Basic tutorial about nav mesh in unity will answer all the questions you just asked
(I mean the actual issue with the sheep is that they allow themselves to be pushed, will making them navmesh agents solve that? I think navmesh solves a different problem?)
you make them kinematic with collider
Well... It's "fixed" as in I figured out why sheep behave different than zombies: they were on different layers, I've put them on the same one and now it works (as I expected too), now my problem is I don't really get why it works since looking at the collission matrix my default and enemies layers look the same to me. But it's on my list of things to cleanup, I have way more layers than I need. (when I started this project I added layers to prevent collisions that I would temporarily reassign objects to, and have since learned I can simply disable the collider)
in a 2d topdown game how would i make furniture / items revealed by light
Is this because the physics takes time between processing the rotation?
private void Awake()
{
rPoint = Random.insideUnitSphere * 0.2f;
//rb.rotation = Quaternion.LookRotation(rPoint, Vector3.up);
rb.MoveRotation(Quaternion.LookRotation(rPoint));
}
//this don't work, always goes to world forward
void Start()
{
rb.AddForce(transform.forward * forceAmount, ForceMode.Impulse);
}
//this works
IEnumerator Start()
{
yield return new WaitForFixedUpdate();
rb.AddForce(transform.forward * forceAmount, ForceMode.Impulse);
}```
updating the rb rotation happens after the physics step, its not about it taking time to process. its just that it hasnt run yet
that makes sense, thank you!
Depends what you mean. Fog of war ?
Hi.
Why does the first time I do the checking it works fine, but the second time it gives me an warning?
while (queue.Count > 0)
{
var current = queue.Dequeue();
if (GenerationManager.Tilemap.GetTile(current) is WaterTile)
return path;
var neighbors = GenerationManager.GetAdjacentNeighbors(current);
float value = IslandValue[current.x, current.y];
foreach (var neighbor in neighbors)
{
float currValue = 0;
if (!GenerationManager.Tilemap.GetTile(neighbor) is WaterTile)
{
currValue = IslandValue[neighbor.x, neighbor.y];
}
}
}```
The warning is "the given expression is never of the provided type"
Which is kinda of odd, as I'm checking for another position, I'm not checking for current again
GenerationManager.Tilemap.GetTile(neighbor) is never WaterTile
Pretty sure it is what your error means
I know what it means
Or GenerationManager.Tilemap.GetTile(current)
Mostlikely WaterTile does not inherit from the tile class
It does. The first check works fine, only the second gives me an warning.
Does WaterTile inherit from TileBase ?
Can you replace the var
And give use the return type of the function
Oh lol
That it is because you are using !
Pretty sure you need to do !(...)
Otherwise it is going to be bool is WaterTile
you can also use is not
Last time I tried unity cried
Does it works on Unity ?
it should in the latest versions
Maybe I was using an older version
I totally forgot not was a keyword
Hey I'm getting a MissingReferenceException: The object of type 'PlayerSpawnManager' has been destroyed but you are still trying to access it.
I have no clue how that happens, not destroying the PlayerSpawnManager anywhere... Can somebody help? Relevant code:
public class PlayerSpawnManager : MonoBehaviour
{
private void OnEnable()
{
PlayerScript.OnPlayerDeath += StartRespawnPlayer;
}
private void OnDisable()
{
PlayerScript.OnPlayerDeath -= StartRespawnPlayer;
}
public void StartRespawnPlayer()
{
StartCoroutine(RespawnPlayer());
}
}
public class PlayerScript : MonoBehaviour, ICanDie
{
public delegate void PlayerDied();
public static event PlayerDied OnPlayerDeath;
public void TriggerDeath(DeathCause causeOfDeath)
{
OnPlayerDeath?.Invoke();
}
}
public class DeathZone : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent(out ICanDie entity))
{
entity.TriggerDeath(DeathCause.DeathZone);
}
}
}
pls ping me with answers
Please provide the error details properly. We don't even know the file name and line that throws it...
sry one sec
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <10871f9e312b442cb78b9b97db88fdcb>:0)
PlayerSpawnManager.<OnEnable>b__17_0 () (at Assets/_Scripts/Managers/PlayerSpawnManager.cs:74)
PlayerScript.Die (PlayerScript this) (at Assets/_Scripts/Entity/Player/PlayerScript.cs:105)
PlayerScript.TriggerDeath (PlayerScript this, DeathCause causeOfDeath) (at Assets/_Scripts/Entity/Player/PlayerScript.cs:100)
DeathZone.OnTriggerEnter2D (DeathZone this, UnityEngine.Collider2D other) (at Assets/_Scripts/Environment/DeathZone.cs:16)```
Share the whole PlayerSpawnManager in a code paste site !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What happens when the player dies? Or was supposed to happen.
atm it only calls Destroy(this.gameobject);
besides invoking the event
You should always check for nullability in OnTriggerEnter
When you destroy a game object in it
Can someone gelp
when i try to add a mod vent the vent goes away but the colider dosent Help?
thanks a lot that worked
๐
Please
try adding the flunx to the gronkle, then press the button. that should work ๐
Seriously though, look at the #854851968446365696 on how to ask a question. No one knows what you're asking
Ok thanks but what is flunx and gronkle
its the same thing as a mod vent. I have no clue!
ok thanks
From a quick google search, i assume you're modding a game. Modding isnt really allowed here though, so ask in the game's related community
I'd say that they need a plumbus.
another question i have: Is there a way to freeze the game while still having coroutines with time working? Or is there a workaround for timed methods?
with freezing the game i mean player, enemies their animations etc.
Maybe would be good to still have UI animations playing
Nope im making my own game thanks for that
@woeful sigil could you please be more specific in your question? We don't understand what you are asking.
how can you write to the shadow map?
It depends on how you yield in the coroutine. Some yield methods would wait real time, some game time, some would wait one frame.
Typically, you don't want to "freeze" the game in the literal sense, as that would make it unresponsive and the os would kill it at after some time.
If you want to pause some objects is setting Time scale, but that's considered a bad practice. The recommended way is to have a pause system integrated into all your game logic.
I don't think it's straightforward or even possible. It doesn't seem like unity exposes the shadowmaps for you to access๐ค
Maybe this could be useful:
https://forum.unity.com/threads/access-screen-space-shadow-map-texture-in-urp.923399/>
Also, for questions like that, there're #archived-shaders and the render pipeline channels.
i think I remember looking into it and basically you dont
To expand on dlitch comment, the approach I use in my game is a enum that determines my games state in a static class, that static class has a public property with a event things can sub/unsub to (similar to a Observer pattern), so for example, when a enemy spawns they can call GameManager.onGameStateChange += DoSomething;, then "DoSomething" takes the GameState enum and I can do things like gameObject.enabled = state == GameState.Playing, I can also toggle input for certain UI this way, and for classes that dont use Update/coroutines/unity events I can setup a local bool to be toggled based on the event, this is what works fine for my game, maybe this approach can give you some ideas
that's exactly what I did!
public Gun LongGun;
public Gun HandGun;
public int LongGunAmmo;
public int HandGunAmmo;
}```
Is this the write naming scheme for LongGunAmmo and HandGunAmmo?
It is CamelCase, which if you want public variables to be CamelCase is indeed the right naming scheme
Some use pascalCase, but as long as you're consistent, either is right
you have that backwards
camelCase, PascalCase
but yeah, some people use PascalCase for public fields and some people use camelCase
I prefer to just use camelCase for fields and PascalCase for properties
Dang it, I second guessed myself. I was gonna do that first haha
don't forget SHOUTY_CASE
it was more in regards to the naming scheme rather than casing.
HandGunAmmo
vs
Ammo_HandGun
handgunAmmo
There is no right or wrong there
The two hardest things in coding are Cache Invalidation, Naming things, and One off errors
Or handGunAmmo or AmmoGunHand (<- my favorite one) or ammoHandgun or or or lol
thanks!
yea, it really does come down to preference (working solo ofc)
https://paste.ofcode.org/34B8BRAVprQxMVxuHKnDNyG
can anyone look at my player script and tell me what im doing wrong? i'm trying to get the jump to work but it doesn't work at all. the function is being called but it still does nothing. tried bumping up the jumpForce to 100 to see if it was just too low and that didnt do anything either. any help on this?
i followed Brackeys video on it almost exactly, except i used the new input system so i had to adjust some things but maybe i didnt adjust them right
You're jsong a character controller AND a rigidbody. Big nono
Also, you are multiplying deltaTime by mouse input
Ah, I see you said Brackeys, yeah. Classic Brackeys error
sorry where am i using the rigidbody?
Just realized I misread it. Saw velocity and jumped to conclusions
ah
the mouse movement works perfect for me. everything from the video seems to work except the jumping part
I'm seeing two Move calls though? This is pretty convoluted
idk man its just what he had in the video
Brackeys is terrible.
https://gamedev.stackexchange.com/questions/178496/mouse-movement-with-deltatime#178508
Mouse input is ALREADY a delta. And i see your sensitivity has to be 100 to counteract this issue?
I see someone else being told not to do it on the other channel haha
#๐ปโunity-talk message
okay ill look at that later then. any ideas for the jump
Is the "Velocity inside Jump" debug showing up?
yea the function is being called
Well I heard that before, just wanted to make sure the SECOND log was showing.
Alright what value does it say?
Oh, I bet it's the first if in Update
You are setting playerVelocity.y there, and that would happen after the callback
No, nevermind. That is only when under 0...
So back to wondering what value it shows
Ok, you see the issue?
Specifically the "Velocity after adding gravity" part?
It's negative by the time you do the Move where you pass in the jump call.
yea i saw that. just having trouble figuring out how to get that part to work
fixed it
you know in games like getting over it, where you can use the arms to crawl around, and they move accordingly to how you drag your mouse around, like retracting and stuff
How could I replicate that in 2d?
2d bone animations
- ik
how do I approach scene management without strings? I made a wrapper object of ScriptableObject type to store all scene data in it per level, store them in a List, but I still need somehow find a way to find them in the List by some sort of key passed in a Load method without strings, cause they are too error prone and not flexible as a key
it's so basic problem (I think), but I struggle with "non-string" solution
you could use an enum
Just use SceneAsset for the editor, to setup values in inspector. Then have those directly assign the name to the string OnValidate
hi - we're using build automation in devops to cook multiplatform builds, using BuildPipeline.BuildPlayer(options); etc - this works fine but on windows it produces an executable file without ".exe" on the end, which confuses people we share with - is there a way to control the output executable file as part of the options?
That sounds like a bug (which you should report). The only thing i can think of is use System.IO to rename the file
Need some help about input on unity
Hey guys. Any reason why the below code with start at the camera then point towards the ground? I thought transform.forward would keep the same Y axis and put the line staight infront of the camera.
Gizmos.DrawLine(Camera.main.transform.position, Camera.main.transform.forward * 10);
Thanks. Thats for my debugging but I cant see why im not triggering my debug when hitting a collider...
nvm. Using a 2d collider in a 3d game and wouldnt find the 2d. Thanks for helping cause now I can continue debugging.
Why might my Capsule be flying all over the place when a HingeJoint is created upon collision?
Note: The flying all over the place only happens when I am holding a movement key (WASD) at time of collision. Otherwise, it behaves stable-y.
rigidbody characterController Smoothy.cs https://hastebin.com/share/epemenawur.csharp
MyKeyInput.cs grabs keyboard input https://hastebin.com/share/ozaxiwehon.csharp
^ -- these are the only two scripts on the Capsule
BarLogic.cs is the script on the bar that the Capsule collides with before Capsule goes crazy https://hastebin.com/share/owecezekaj.csharp
Gif of issue: https://i.imgur.com/skB5tWk.gif
also, if the issue is because of anything in Smoothy.cs being active at the time of collision, this confuses me because in BarLogic.cs I am disabling Smoothy.cs upon OnTriggerEnter. so how could it possibly be a problem with code in Smoothy.cs if colliding with the bar should instantly disable it? (I'm noticing that if I remove the //Rotation code in Smoothy.cs that this spazzing out & flying around doesn't consistently happen anymore, but since I'm already telling the code via BarLogic.cs to "Disable Smoothy.cs upon colliding with Cube", I don't know what more I'm supposed to do.)
You need to make sure the extension is included in the build path passed to buildplayer. It doesnโt assume anything or adds extensions automatically. That is true for several platforms, but not all.
I've got a GameManager with DontDestroyOnLoad that checks which Scene has been loaded and starts an initializing routine on it's specific manager:
{
switch (scene.buildIndex)
{
case 1: //overworld
StartCoroutine(OverworldManager.Instance.Initialize(playerPosition, timeOfDay, map, entryPoint, overworldSceneCode));
break;
}
}```
But when I initialize it on OverworldManager, it gives me an error on this line:
```public IEnumerator Initialize(Vector2 playerPos, TimeOfDay timeOfDay, string mapName, string entryPoint, string overworldSceneCode)
{
yield return 0;
pathfindingInjector = GetComponent<PathFindingInjector>(); <--
yield break;
}```
```MissingReferenceException: The object of type 'OverworldManager' has been destroyed but you are still trying to access it.```
Btw, the second code snippet is being executed in a component of the object that has been destroyed, what am I missing?
your game manager is ddol
how about your OverworldManager
It ain't
But the switc in OnLoadedScene should assure there is an OverworldManager in the scene
Also, this was working perfectly yesterday xD
wrong overworldmanager
There is only one in that specific scene
no, you misunderstand
the game manager is refering to the overworldmanager in the first scene, that no longer exists
So, OnLoadedScene is executing before switching scenes?
the ienumerator is belong to the destroyed manager not the new one
no idea why it worked
Does Awake() execute before OnLoadedScene?
In any case, this should fix it, but it doesn't:
{
switch (scene.buildIndex)
{
case 1: //overworld
OverworldManager manager = GameObject.Find("OverworldController").GetComponent<OverworldManager>();
StartCoroutine(manager.Initialize(playerPosition, timeOfDay, map, entryPoint, overworldSceneCode));
break;
}
}```
Well, I also should have said that the OverworldManager is a singleton
it may help
you can have a look
I'm making a game with randomly generated dungeons, so I made it that when the dungeon is generated the NavMesh is baked, but the doors don't connect for some reason, does anyone know why? (The agent size is small enough for it to connect)
I'd have said to reduce the agent size but that obviously hasn't worked
tried setting it to zero?
I mean I created by hand 2 rooms and it did connect, I think it has to do something with the generation (Im using DunGen)
Here i placed the rooms by hand, and it did connect
I set it to zero, also didn't work :/
Hey everyone, I have an item attribute system that currently looks like this:
[System.Serializable]
public class ItemAttribute
{
public ItemAttributeType type;
public ItemAttributeValueType valueType;
[EnableIf("valueType", ItemAttributeValueType.Float)] [AllowNesting] public float floatValue;
[EnableIf("valueType", ItemAttributeValueType.String)] [AllowNesting] public string stringValue;
[EnableIf("valueType", ItemAttributeValueType.Color)] [AllowNesting] public Color colorValue;
[EnableIf("valueType", ItemAttributeValueType.Vector2)] [AllowNesting] public Vector2 vector2Value;
[EnableIf("valueType", ItemAttributeValueType.Vector3)] [AllowNesting] public Vector3 vector3Value;
}
public enum ItemAttributeType
{
durability,
containerSize
}
public enum ItemAttributeValueType
{
Float,
String,
Color,
Vector2,
Vector3
}
I was wondering if it's possible to somehow link each ItemAttributeType enum with an ItemAttributeValueType? For example I'd want the durability ItemAttributeType to be linked with a float ItemAttributeValueType.
hi, trying to render the gun separately, doesnt render the gun (i know the weapon looks trash, just a prototype)
you have your camera culling mask set to weapon which is the same layer as your gun
shouldn`t it be like that?
ah, you could be right, culling mask is an inclusive mask
fixed it, had to put it in the stack
Am I missing something, or is UI toolkit not as clean as the legacy UI stuff when it comes to callbacks? Asking because having to query the DOM by element IDs to set callbacks seems like a downgrade from how legacy UI lets you define onclick stuff in the inspector. Is there a better way?
If I understand correctly your situation, not without Code Generation. However, it seem to me that you might want to explain what you are trying to achieve instead. We might be able to find an alternate way.
I'm basically just trying to create a flexible attribute/stat system for my items, but with multiple value options for each attribute instead of just, for example, a float.
You should explore the usage of Polymorphism + SerializedReference. I am 90% sure it will fit what you need.
I'll do that, thanks
Something like the following.
[System.Serializable]
public class ItemAttribute
{
[SerializeReference]
public List<IValue> floatValue;
}
[System.Serializable]
public interface IValue
{
}
[System.Serializable]
public class ValueGeneric<T> : IValue
{
[SerializedField]
private T value;
}
public class FloatValue : ValueGeneric<float> {}
public class IntValue : ValueGeneric<float> {}
Whatโs the most optimized way to make a 2D light flicker script
might as well do a public interface IValue<T> { T GetValue(); void SetValue(T value); }
What Iโm doing now is just taking the light intensity when the script initializes and then adding a random value 0.01-1 to it and then tweening to that
Pretty sure that you will not be able to hold the reference in a list
hm fair enough
That should pretty much work correctly. Alternative that could be more optimize would be way too much trouble and you probably will have a lot of other things that will need to be optimize and will impact more.
this is a code channel. perhaps you want to ask in #โ๏ธโphysics
ok sorry
hello everyone, im looking to make this (image)
from https://youtu.be/HQqZ8z2q96I?t=70
idea: have the entire scene or an area of the scene shown in a specific area
Who will win?
Red VS Blue
Destroy the opponent's base
Thank you for watching :)
[ Content information ]
-
Destroy the opponent's base and win.
-
If the base HP is below 500, it will be invincible for 10 seconds and attack faster.
-
The base makes a basic attack. Additionally, it fires a counter-attack missile as much as the damage ...
any tips are welcome, including some name for it, since i dont know what this is called
thanks!
that's just a second camera rendering to a RenderTexture and displaying the RenderTexture in the UI using a RawImage.
thats super useful thanks
hey, so i want to have my camera switch between different angles a la silent hill 1, what would be the best way to go about it?
I got two solutions im thinking of and can't decide on the approach:
- Multiple cameras i flick between disabling/enabling
- One camera, switches between transforms sat as empty gameobjects
which way would be best out of those in regards to efficiency, or is there another way i haven't thought of? TIA
Cinemachine can do this for you.
just set the default blend to "Cut".
this will make it easy to give each camera angle different settings (notably, field of view) without needing to juggle lots of cameras and keep the rest of their settings consistent
brilliant, thank you! ๐
so i've never used cinemachine before so gonna dive into docs, but before i do, would specific cameras also be able to pivot to look at player?
i.e. camera 1 is just a static angle, but camera 2 would look at the player and follow while at a static position
nvm answered my own question XD
yeah, there are lots of aim options
coolio, thank you
Also, if you're just starting to use Cinemachine, you can choose between 2.0 and 3.0
I use Cinemachine 3.0 everywhere now
Both work fine and both will be supported for a long while
It cleans up a few pain points (for example, 2.0 has a whole special kind of third-person orbit camera)
the API also feels nicer; 2.0 uses that annoying m_ prefix everywhere
@proven plume build path looks like a directory tho? is that an additional buildoption?
i think this is correct channel for that, whats the best solution for player controller if I want it to interact a little bit with physics? my current is using capsule and MovePosition and it moves many objects that are too heavy, clips to walls etc, ChatacterController doesn't use physics besides od gravity i think? any idea what can I use?
What does "interact a little bit" mean
CharacterController indeed doesn't care about physics. It does respect colliders.
actually, I'm mildly surprised you're able to push objects around
yes I'm using rigid body
possible to move small objects not a whole 500 mass car
move your object with forces and give it a realistic mass and realistic forces
also 500kg is quite small for a car
you mean move player with addforce?
here's what happens now
and it's possible to flip whole car with player controller
I'm just working on the settings menu for my game and I'm a bit confused with how AA works when you are camera stacking.
MSAA * 8 in the URP settings, yet disabled on the camera?
Is there an override setting or is something else happening?
your car is too light, your player is too strong
but also realistic physics limitations are hard to put into a game. In a game you can always add forces no matter what. in real life you need some other object to leverage against, or you can't actually push
player is just 40kg
even when I would put car to 1000kg player will be able to flip car
but also realistic physics limitations are hard to put into a game. In a game you can always add forces no matter what. in real life you need some other object to leverage against, or you can't actually push
the amount of forces you're adding to the player - also relevant
but when I will add less force player is too slow
that's why I'm asking for anything different than MovePosition
Forces
Haven't used the old input in a bit, is there a nicer way to do quick key presses?
namespace Controllers
{
public class InventoryController : MonoBehaviour
{
private void Update()
{
HandlePotentialSlotSelection();
}
private void HandlePotentialSlotSelection()
{
if (Input.GetKeyDown(KeyCode.Alpha1)) HandleSlotSelection(0);
else if (Input.GetKeyDown(KeyCode.Alpha2)) HandleSlotSelection(1);
else if (Input.GetKeyDown(KeyCode.Alpha3)) HandleSlotSelection(2);
else if (Input.GetKeyDown(KeyCode.Alpha4)) HandleSlotSelection(3);
else if (Input.GetKeyDown(KeyCode.Alpha5)) HandleSlotSelection(4);
else if (Input.GetAxis("Mouse ScrollWheel") > 0f) HandleNextSlotSelection();
else if (Input.GetAxis("Mouse ScrollWheel") < 0f) HandlePriorSlotSelection();
}
...
Nope, that's essentially it
Ok
Is there no way to do a copy in code? so in code call something that for example copies the color red and then i can right click on a color in the inspector and paste that color
for (int i = 0; i < 5; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
{
HandleSlotSelection(i);
}
}
(not tested, might need to add casts)
you could do:
KeyCode[] slotKeys = new KeyCode[] { KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4, KeyCode.Alpha5, ... }; // or assign in the inspector
for (int i = 0; i < slotKeys.Length; i++) {
if (Input.GetKeyDown(slotKeys[i])) HandleSlotSelection(i);
}```
An editor script could probably do it.
you'll want to ask in #โ๏ธโeditor-extensions
Sure yeah, i can do that. but is there no internal copy function that can do this?
this script would be using that internal code
although, "internal" might be unfortunately literal here: I'm looking at the Clipboard classes, and they're all internal
e.g.
Oh so it's internal internal, not in like InternalEditorUtility or somethiong like that. That's unfortunate. Thank you
I'm not very experienced here, so I might be wrong! definitely ask in the other channel
Ok i will. Thank you
Build scripts
I'm making a system for navigating a map. All points and ships are stored within the generator. What's the best way to go about saving the "PoissonGen" object so I can say go to a combat scene and come back to the same map? (Ive seen a couple different ways of doing this but I just want takes on whats the best way to go about this)
Ideally, you would generate this data in a format that can be more easily saved than a GameObject hierarchy. Then you can create the GameObjects from that data representation.
bingo
I'm using a bidimensional array to instantiate GameObjects, which works perfectly when the size of the object is 1, but they overlap when they are bigger, any ideas how to fix it?
You would have to show your code and explain what you mean by "when the size of the object is 1"
On a basic level, you will need to adjust the spacing you're placing things at by the size of those things
private float distance;
private char [,] map = {
{'x','x','x','x','x','x','x','x','x','x','x','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','o','o','o','o','o','o','o','o','o','o','x' },
{'x','x','x','x','x','x','x','x','x','x','x','x' }
};
void Start()
{
for (int i = 0; i < 12; ++i)
{
for (int j = 0; j < 12; ++j)
{
if (map[i, j] == 'x')
{
Instantiate(wall, new Vector3(i, 6f, j), Quaternion.identity);
}
}
}
}
- don't hardcode 12, use
map.GetLength(0)andmap.GetLength(1)to get the actual lengths of the array. - don't just use i and j as the coordinates directly. use
i * itemWidthandj * itemHeight
you will need to provide the item width and height somehow
it works now thank you :D
Does anyone know how to create code for determining where a player should aim in order to hit there target based on velocity of the enemy and position of the player.
I am getting this error:
Objects are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!
UnityEditor.Graphing.GraphObject:OnBeforeSerialize ()
My game is running still but i d like to avoid corrupting the project so how do I figure out whats causing it.
What is the expected behavior of UnityWebRequest.Get(url);? If I do UnityWebRequest.Get("asdfasdfasdfasdfasdf") and yield on it in a coroutine, it NEVER completes (I would expect it to end quickly with an error). If I paste a valid uri in a browser to where I actually want to GET from, I get the expect JSON blob response, but if I use UnityWebRequest.Get for that same uri, it just yields endlessly and isDone is never true. Obviously there's a error going on here, but Unity's API seems extremely unhelpful.
EDIT: nvm I wasn't calling SendWebRequest() after creating it ๐ฅฒ
show current code
put it in a tryGet and use a timeout
Is there any difference between putting in an invalid URL, like "asdf", vs a valid but inaccessible url like "http://doesntexist.asdf" ?
By default, Unity web requests don't have any timeout, so that could explain why it never gives up trying to connect.
Here's an example, this seems extremely broken to me, obviously www.google.com is valid and obviously I have internet:
[MenuItem("Tools/Test Google")]
public static void GetGoogle()
{
_instance.StartCoroutine(_instance.GetGoogleCoroutine());
}
private IEnumerator GetGoogleCoroutine()
{
var www = UnityWebRequest.Get("www.google.com");
while (!www.isDone)
yield return null;
Debug.Log("this never happens");
}
omg I need to call SendWebRequest don't I
I'm dumb
I've created different LOD grass blades in blender by removing certain vertices. I had to update the UVs too. When I set my texture to a sine wave in my shader, I get this. How have I managed to fuck it up this bad? XD
uv mapping is different on different models
or anything else you depend sin in your shader
Yeah thought so, I'm just absolute trash at blender so im not sure how to fix it
i think its about modelling not scripting
I assume as long as the UV is the same size, I just have to distribute it evenly?
Yea i think so
you can always use sin on model y axis
instead of uv coord
hows this. a code question
okay buddy i didnt know did i
oh really? ill take a look at that
do you just blindly post in any channel without rading their description 
shaders are code
would u just mind your business if your not gonna help smh
i made a code that instantiate popup text with the damage. i asigned a empty object to instantiate to but just the x is good and y is wrong.
any idea why those 2 hinge joints behave differently?
first one is created with add component
second one is created with script
if (part.hidgeJoint != null)
{
// create HidgeJoint that will hold door to parent
HingeJoint hinge = part.gameObject.AddComponent<HingeJoint>();
hinge.axis = part.hidgeJoint.axis;
hinge.anchor = Vector3.zero;
hinge.connectedAnchor = part.position;
hinge.connectedBody = gameObject.GetComponent<Rigidbody>();
hinge.useSpring = false;
hinge.useMotor = false;
hinge.useLimits = true;
hinge.limits = new JointLimits() {
min = part.hidgeJoint.min,
max = part.hidgeJoint.max
};
hinge.breakForce = Mathf.Infinity;
hinge.breakTorque = Mathf.Infinity;
}```
mind not flooding code chat with this unrelated nonesense
mind leaving it to the staff bud
go ahead, see what they say
guys dont be jerks to each other
to the second I cant apply any force at all, it stays still
like limits would be set to 0 0
Can somone help me.
fr
no memes
i mean the text spawn below the characther but at the right x
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
is ok or should i send the full code
this is useless to send
christ arent you just a โจ bundle of joy โจ
why dont you kindly fuck off
stop guys jesus isn t ok with you arguing
i mean in another scene is working perfectly
Instantiate(popupdamage60, estantiate.position + Vector3(0, 2, 0), Quaternion.identity);```
so i don t think is pivot
how can I get all files in a folder (all wavs, audio clips) and add them to a list of type sound clip
Directory.GetFiles
and if i want a different y in another scene then what
no idea you should give more info
what assembly does it needs ?
you didnt even mention before scenes
some guys should just buy copilot or use google
@timid depot Don't post off-topic images
sorry
ty
any idea?
looks likes for web, i got mines locally
its for any url
including local urls
aka your pc
depends where you want to get them from
okay ty ill try
my project
Application.persistenDatapath is usually where the root should start
if you only want files from the project just use Resources.LoadAll no ?
the goal was that i could just drag and drops all my music, convert to audio clips and generate the list
withotu me adding one at the time the music to a list in inspector
Oh ok
thought you meant you wanted external audio from pc to a build
ah sorry
https://docs.unity3d.com/ScriptReference/Resources.LoadAll.html
this should work
no i just want a "get all music here and then do stuff"
perfect ty
but this forces me to create a Resources folder ?
indeed
can i see it from the Project window ?
i only got packages and assets
i manually created it in the file explorer
wdym just create the folder anywhere in your project
yeah Assets
ressources has to be in Assets ?
yes
you can have multiple ones but they have to live in Assets
if (part.hidgeJoint != null)
{
HingeJoint hinge = part.gameObject.AddComponent<HingeJoint>();
hinge.axis = part.hidgeJoint.axis;
JointLimits limits = hinge.limits;
limits.min = part.hidgeJoint.min;
limits.max = part.hidgeJoint.max;
hinge.limits = limits;
hinge.useLimits = true;
hinge.connectedBody = gameObject.GetComponent<Rigidbody>();
// set hinge position to local position
hinge.anchor = part.position;
}```
any idea? I cant fix it for 20 minutes
works when I add hinge joint with unity ui but not with script
hinge.anchor = part.position; this is almost certainly wrong
since part.position will likely be a world space position
part.position is local position
of what
where part should be attached
but the joint is on the part
the anchor needs to be the local space of the connection point in the part's coordinate system
I dont get it
You did this:
part.gameObject.AddComponent<HingeJoint>();
so the joint is on part.GameObject
Where is the connection point supposed to be?
Ill try wait
because the part is at 0 in its OWN local coordinate space
part.position is the part's position in its PARENT's coordinate space
yes
the joint anchor needs to be in the part's coordinate space
now its inside parents center
not parts center
with my code position is correct but cant move it
I still have no idea it behaves so weird
if i made a public TextMeshPro in a script. How can i put in a prefab that has a textmeshpro.
Drag and drop
but most likely you used the wrong type
it dosen t work
Hey guys don't know if it's the correct place, but I'm having some trouble making a build on WebGL in UNity 2022.3.5.f1. I'm getting this error:
Building Library\Bee\artifacts\WebGL\GameAssembly\release_WebGL_wasm\namrvu51moua.o failed with output:
C:\Git\AirConsoleMovingOutMad\Library\Bee\artifacts\WebGL\il2cppOutput\cpp\DevmUnityLibV2.cpp:6639:9: error: no matching function for call to
There is more, but it's nothing specific in my code, just related to this Bee folder.
ok
if i have in code Text.text = "80" + 5%maxheal
it should be idk 83 or smh
but is 803
"80" is a string
you cannot add an integer to a string and expect it to increase the string's number. + is used for concatenation with strings. it will not do math
so how can i
use a number not a string
use a number to do your math then convert it to a string
you cannot do math on strings
int num = 80 + 5 % maxheal;
myText.text = num.ToString();```
Howdy howdy!
Anyone know if it is possible to detect camera exposure changes in Unity for mobile devices and webcams? I am interested in tracking the change in brightness/gamma on images.
A field initializer cannot reference the non-static field, method, or property 'Player.maxhealth'
it gives me this error
your code needs to go inside a function
you can't write arbitrary code outside of a function
i think he might need basic C# training/tutorial
maybe anyone was creating before hinge joints between two dynamic rigid bodies with script and can share snippet? my code still doesn't work after 2 hours of debugging
works with unity ui but not with script
What about it doesn't work?
Player Character Inside a Shape Problems
Im having a problem that I would of expected to be easy but is driving me insane and not working....
This is for Quest VR... I have a ground plane (with a mesh collider to keep from falling thru) and a player with a character controller. All works as expected. I want to put the character INSIDE of a cylinder or a capsule and have it contain the player. I want the player to collide with the inside walls if they try to get out.
So i've tried both a cylinder and a capsule both with a capsule collider. I make them much larger than the player and the character controller. The problem is both options immediately forces the player OUTSIDE of the object. The collision then works and I can't get back into the shape.
For trouble shooting I tried with a cube and a box collider this time the player stayed inside the shape but went right thru the wall but then it gets blocked trying to go back inside. I even tried each shape with reversed normals. That didn't work either and it would eject anything in the space with a rigid body. Anyone have any idea whats wrong here????
You are not using the collider correctly. A player will always be ejected from the collider.
I'm genuinely stumped.. what's the issue here? Gamemode is the class I'm inheriting from which is meant to just make life easier and then MeleeGamemode is well.. the gamemode
It refuses to add listeners and I have to do it manually in the inspector
You need to either create a mesh or place multiple object around the player. I recommand ProBuilder if you are not familliar with 3d editing tool.
(For the record just so I don't look stupid the quit was for testing. The loop never quits the app despite the fact the participatingPlayers is always correct before it)
Okay nevermind fml it was script execution order
Should definitely be using start instead of awake for gamemodes anyways
Application.Quit inside a foreach loop. Why?
Hello, I don't really know in which category my question falls (beginner - general - advanced) so I'll put it here.
I am questionning myself regarding json conversions of things such as ScriptableObjects. If an Object holds a SO when converted, what happens ?
Also, if the "connection" got cut during the conversion, how to establish it back during the re-conversion from json to an Object ?
I've been getting into a bad habbit of using Application.Quit because its immediate and I'm going to have to edit the script anyways lol
I need to break it at some point it just kind of came out of nowhere
Application.Quit does nothing in the Editor
Dont. How do you expect code to execute afterwards?
You're better off actually using the debugger with a breakpoint
Its not meant to.. kind of
return; then?
except your addlistener perhaps?
I've never used the debugger but I'll look into it at some point
Wdym
It was because of script execution order not the quit
But yeah I got rid of the quit after the screenshot
I should've mentioned that
public void ChangeColor()
{
var color = new Color(Random.RandomRange(0, 255), Random.RandomRange(0, 255), Random.RandomRange(0, 255));
Debug.Log(color);
foreach (Transform child in ore.transform)
{
var spriterender = child.GetComponent<SpriteRenderer>();
spriterender.color = color;
spriterender.material.color = color;
}
}
I am trying to change the colour of each of the Square sprites under the Ore GameObject. But when I run the above method, they all change to white regardless of the Color() that is created
new Color() takes floats ranged from 0 to 1, use a new Color32() if you need to use bytes (0-255)
Both of them convert to each other and back, seamlessly
Oh that explains it! Thanks ๐
Could always
but I don't know what you mean referring to the connection. Json is just text, where the field name and values are written. You read it back and it populates the fields.
Usually I make my own separate classes which holds only the information I want to save. If you need to save which SO was used, I would save it by some ID then map ID to SO
If you had HDR on, your color would have a lot of intensity. That's how you make HDR colors, pass values greater than 1 to new Color()
That's what I had in mind too. I guess I'll go with that unless I find something better.
To give you an idea of why I asked :
- I have a class Character which just has attributes that will be modified compared to the SO it originates from (eg. the level).
- It also has the SO as an attribute to seek the attributes that will be never-changing (eg. the name).
I did that to avoid having 300 Characters originating from the same SO having unnecessary common and constant attributes. I feel like it's more optimised memory-wise, etc... Still I need to store them in a json text file which is why I was concerned with SO "connection" (which is just an attribute)
Please do correct me if my thought process is wrong or if you see better options.
300 characters with a bunch of float will not be a memory issue at all.
I also have lists, arrays & dictionaries though. They hold a very limited amount of data still
I have a crosshair sitting on top of a render texture. I want to raycast to the far back from the crosshair position.
I'm trying to calculate the raycast from the crosshair position inside the RenderTexture, to shoot from the camera that renders it. ```Vector2 screenPosition = RectTransformUtility.WorldToScreenPoint(mainCamera, this.transform.position);
// Create a ray from the screen position
Ray ray = mainCamera.ScreenPointToRay(screenPosition);
Debug.Log(screenPosition);
return ray;```
How many byte of memory do you think it holds ?
It returns ridiclous values like X:709584, y:459434, 0
Lets say its about 20 data structures holding an average of 10 strings/integers
So not that much I guess
Exactly, memory is not a concern here. However, usability is. I believe it is way more simple to reuse the data then reenter it each time.
In fact, I didn't see the problem from that angle, I unnecessarily worried over optimization where it didn't really matter
When you mean "reuse" it, do you mean it's better to just have the Characters have all the attributes and never look at the SO again or do you mean that my initial solution is better ?
only worry about memory if you are being wasteful, or memory cost is getting large
I mean, if you have a character, you want to use the character instead reentering its image, name and whatever each time you use it.
300 characters is like one discord message lol
When I meant characters, it's not symbols, I mean units with names, abilities, etc...
unity would serialize that as a reference, unless you are defining the whole character there
and if youโre defining the whole character there, well it needs to get defined somewhere
i have my SOs reference other SOs ina field all the time. It literally costs as much as one reference
guys, is there some good free resources of making ui management system from scratch? tutorial or good repo to check is fine
not something very complicated, just management of a panels, buttons and decoupling them from main logic by some way
I'm trying to make ui for my game, but it's so clunky and I dunno how things done right for this problem
like quite good examples of making an ui system, not just "how to make a button with functionality", etc.
maybe something with mvc, dunno (I'm not very proficient in mv-family patterns to implement it, it's just for example)
Okay thanks, I'll look into that a bit deeper on the internet.
Also thanks @steady moat, I'll be keeping that in mind !
I dont follow... can you clarify. How to do this then? Do i have to build mutliple shapes around the player to contain them???
Im not sure of any specific resources I can send, though with my UI, I use events and serialized classes so I can setup canvas-specific references like text, images, etc, and the UI can just respond to events and update itself when things change, the event itself can pass whatever dependencies are needed (such as the player if the UI needs to display the current health for example, or the player can fire a "onDamage" or "onHealthChanged" event and pass its current health, the UI can listen for that) - panels could be handled like a state machine or a stack if you want to allow popping (like spamming the back/esc button), maybe those techniques could help you build your own UI system
What would be the best way to smoothly move an object to another position when you click the mouse?
Obviously if i check for the mouse press and call a function its only gonna run once so it won't smoothly move
You need to be build collider around the area, not have a collider fill the area.
You could use a coroutine and lerp it, or some code in update which tracks if it should be moving. There is no best way for this, it is just moving an object.
Yeah I ended up just adding some code in update, not sure how resource efficient that is tho ๐คทโโ๏ธ
if you want smooth movement, it has to do some moving every frame
don't worry about it
Itd be pretty hard to make this use any resources. At most you'll be storing a speed and direction (which has to exist in any solution you do)
If you are doing this for 1000 objects then maybe start to profile.
So is there any way in OnTriggerEnter to check if the collider that was entered was the one the script is attached to or a child of that collider? Because it seems the only parameter that the event returns is the foreign collider
Compare references by either using GetComponent or cache them somewhere on the script
I know how to do that with the foreign collider, but that's the only collider the function gives me. I want to do it with the more native one
Or rather exclude collisions triggered by its children
Is there a better workflow with singletons? Right now I have a bootup scene which has the singleton then I add DontDestroyToLoad to the singleton
The issue with this is if I want to work in another scene I have to go back to the bootup scene so the game manager singleton actually gets initialized and then navigate through my menu to the scene
Perhaps layering them and ignoring them via the collision matrix, but otherwise I'm not too sure beyond casting yourself and ignoring using a mask.
I'm not sure how I'd do that
The object and its children are already on different layers
I'd expect there's another way, because I'd feel like designing for layers would eat them up pretty quickly for these concepts.
I think I misunderstand what my line is doing:
_spriteRenderer.gameObject.SetActive(slot is { Item: ToolSO or SeedPackSO });
What I want it to do is set the sprite rendered to active only if the item at the slot is a tool or a seedpack, but if it changes from a non-tool or seed pack item to a tool or seed pack item it does not activate
One way if you want to is just add that singleton in all scenes and when you swap scenes just don't instantiate if one exists
I considered that but it just seems so hacky
It works but I guess I was hoping there was a more efficient way
Well, considering when you do build it, you'll always start in the boot screen
so temporarily hacky in that sense
Yeah you're not wrong
There isnt really a clean way, since you are starting the game at a point itd never start in
So if I checked off where "Ignore Raycast" and "Ignore Raycast" intersect then this would mean that collisions between two objects on the "Ignore Raycast" layer won't register?
right, you exclude them from physics operations
Alright. I think the problem is that I do want triggers between those two layers to still work, but that I want this script specifically to ignore them. How would I do that?
I'm not too sure about that with collisional events and rigidbodies. I would say just compare layers and ignore them, though I'm not sure how you manage that without doing the casting yourself.
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Perhaps something like that