#archived-code-general
1 messages · Page 353 of 1
ok
well yeah save manager has all the saveables
But how do the objects become saveable
They have to implement it right
yes thats why only ISaveable objects have their own SaveData class for exaample
they need to follow the strict rules enforced by interface
Ok so they do know about it then
thats when it stops it still has 2 meters left?
yea
it really depends, there are a dozen ways to implement this tbh.
Target is not on the ground
no i put it on the ground
It is at y value 257, while your player is at 254
It says right there in the logs
Only thing im not understanding is how it becomes ISaveable for the save manager i get that it sends itself to the save manager into like a list of isaveable or whatever
Ok, irrelevant though
The target is at 257 and the ENEMY is at 254
That is 3 meters above the enemy
Oh, 2.5 about. So exactly the distance you logged of course
ok I will show a quick example
ok let me see than i changed all the numbers of player, enemy and chekcpoints to 256.5
Why 256.5?
That is about 2 meters above the enemy
The enemy is at 254.44
That is what you need to have all the waypoints at if the terrain is flat
Just ignore the Y instead of positioning them at the same height ?
Very good point
i put the transform to 254.44
now its not moving to even one checkpoint
Do what simferoce said
Just check the distance to a vector using the x and z of the target, and ignore the y (plug in the enemies own y value)
I am not seeing any difference. It is still checking distance between transform.position and target
new Vector3(target.x, transform.position.y, target.z)
btw new Vector3(target.x, transform.position.y, target.z) isnt a line in my coe
Is it smth to do with custom attributes? Trying to read up a little
I know. That was the line of code you would use when doing a distance check. It creates a vector at the position of the waypoint in the x and z directions, but at the same y position as the enemy. Thus you would not ever have to worry about it being above or below
so when i make that what do i do
Use it in you distance check, instead of just target by itself
ok
You could also make a variable and set that when you assign a new waypoint as target, so you don't have to create a new vector every frame
But then it would be the y position of the enemy at that point in time and not update
did i do it right?
.. it worked THANK YOU SO MUCJH
not really but you could do it if you want to.
Why not just start with a simple system then go from there? I feel like you might be prematurely creating a heavy system when a simple one might suffice
how much data are you saving from how many different data types
I have one created already and it is pretty simple I was just wondering about the interface approach as its probably better than mine
Currently i just put everything in a PlayerData class and serialize and save that
simple is usually better 🙂
interface adds a whole other layer of complexities
Why use it then
And I am just curious how that approach works
I was thinking about the event option that seems like a good approach too
idk there isn't a specific way to do it thats why i'm wondering what you're trying to accomplish
I have interface but had to use a Dictionary with it but that now adds complexities of GUID and ofc not being able to serialize it with native serializer
Lets say i have a bunch of coins in a bunch of different levels and I want to save if they have been collected or no
my specific usecase was doing items you can store inside Crates / Inventory / Backpacks
so yeah I had to make Unique IDs for each item, because once you pick them up and save, You dont want the game obviously spawning more on Load
this involved doing custom dictionary serialization and it was a pain
I have done that before but not with an interface
you dont technically need the interface but it surely helps
I have a video i watched a few years ago on this
lemme find it
But if you have a save method with the interface wouldnt you need to serialize in there each time
Yes pls🙏
https://youtu.be/cwSKPIvWvpM?list=PL-hj540P5Q1hLK7NS5fTSNYoNJpPWSL24
was either this one or the few videos before/after
🚨 Wishlist Revolocity on Steam! https://store.steampowered.com/app/2762050/Revolocity/ 🚨 This series will teach you how to create a minecraft style inventory system in Unity 3D - this is includes stackable items, with a max stack size and the ability to split and combine stacks, and delete them from your inventory.
I show off everything we will...
Awesome ill watch in a bit
Can you add an ASP.NET API into a Unity solution that gets triggered to run when the Unity project runs? So you don't have to host a API but rather inside the same solution
no
what would even be the point of that
you should not have an API on the client anyway
this is straight up bullying, unity isn't serializing my vector2 correctly...
wait holdon, is it like {"x": 0, "y": 1} or smth
you gotta be joking me if that is the case
why would it not be
it seemed logical it would parse a tuple as a vector
which tuple ? they're different types completely
vector can only contain float/int
tuple can have multiple datatypes
List<string> omg = new();
(List<string> omg, Vector3 position, bool, float) crazyTuple = (omg,transform.position, true , 23.3f);```
well anyway it was an easy fix server-side
oh ok . what was wrong ?
I just had to change how my server represents positions
I mean my server already does a lot of translations to allow easy serialization in unity
my server just saves regular C# classes/struct.
In unity i already convert them to that
eg Vector3 goes into a custom Position struct etc.
I use a class library to do it though so Unity project/objects doesnt have to know any of it
I have custom classes but stuff like the game definitions data has a lot of complex dictionaries which unity doesn't parse so I have a custom serializable dictionary type for that and I have to make my server convert these for unity
umm a debug tecnique but how do I check what keeps resetting my object's position (except idk, going through each script)
search references to that script first
nah it's the animator for damn sake
but like, I only want it to control z
I might just move it out of the animator tbh
but then I need to wait for animations and shit to finish to change the stupid z
I think there was a property you can switch on that only controls the properties changed with keyframes
I'm not good with animator so I'm not 100% on that.
will using assembly definitions noticeably reduce assembly reload times in larger projects?
It will only compile assemblies that have changes
So most of the time yes, unless you make changes to every assembly before compiling
not really a code question
idk where else id ask sorry 😞
well..did you read the #💻┃unity-talk description?
Reload time, no. Regardless of which assemblies get recompiled, all of the app domain and all assemblies have to be reloaded.
what's the point then? It just seems like a hassle if there's no real reload time decrease
When I say reload time, I'm referring to domain reload. Compile time can still be reduced. After you make a change, Unity recompiles and then reloads the domain.
ah okay
domain reload can be disabled btw
But I mostly use assembly definition files for organization. It means you can separate code and define clear dependencies between them.
For entering playmode, yes, but not for code recompiles.
truth
Domain reload time is far far higher than compile time.
Yeah, this has been my experience as well. Things like IL post processors found in Entities and Burst can inflate compile times, so I can imagine the ratio between compile time and domain reload differs between projects, but almost certainly always leaning towards domain reload.
Not sure about ECS, but I think Burst compilation is async.
Either way though, shaving a second or two off compile time dwarfs in comparison to domain reload taking tens of seconds or even up to minutes.
How can I make sure ENABLE_WINMD_SUPPORT is on?
I've done everything that the Unity docs told me to (IL2CPP, .NET Framework in settings) but my code refuses to believe I have WINMD support (I am on a windows computer)
Are you building to UWP?
I think the app needs to be running in the Windows Runtime to access those APIs, which means the Unity build must target UWP, not Windows Standalone.
I don't know much about Windows Runtime or UWP, but from a quick search, it appears you cannot access WinRT APIs from a regular C# app, for example, without changing the runtime target to a specific .NET version which is WinRT compatible.
getting UnassignedReferenceException on this:
rigidBody?.AddForceAtPosition(direction, hitPoint, ForceMode.Impulse);
rigid null should skip AddForce, right?
can someone explain what that exception is and how to get around it without expanding the ?. into an if ()
https://docs.unity3d.com/ScriptReference/Object.html
This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
this isnt using unitys null check on it
drats! I thought they addressed that.
I guess I'll have to expand all these nice targetObject = tmpTarget.GetComponent<MCUnitChild>()?.gameObject ?? tmpTarget.GetComponent<MCUnit>()?.gameObject; into ugly if then... oddly enough it all worked
except for that one...
unless the rb is being destroyed, im not really sure why the error appears. As far as i know, unitys null check also checks if the object is destroyed
also couldnt that above line just be simplified to
targetObject = tmpTarget.gameObject if it isnt already a game object?
it only sets target if components exist
is there a reliable way to call OnDestroy() for a ScriptableObject? i'm having an issue where something that i thought would be destroyed isn't getting destroyed
You’re not supposed to destroy them dynamically
if you destroy them in the editor (in edit mode) you should handle cleanup with an explicit call to a cleanup method from the outside.
oh im not destroying them dynamically. to be clear, what i want is for OnDestroy() to be called when i exit play mode. i have the following code to destroy a sprite that i create using Sprite.Create(...)
private void OnDestroy()
{
Debug.Log("Destroy called on a theme!");
if (cachedSprite) Destroy(cachedSprite);
}
That’s not how they work. You need to do that some other way. SOs stay loaded in the editor
they do not have a play mode lifecycle
i see. so if i want to store temporary data related to a ScriptableObject, that needs to be done in another way?
Not necessarily, you just have to call that cleanup function some other way
You can hook into the editor application play mode changed event for example (I forget what it’s called exactly)
https://docs.unity3d.com/ScriptReference/EditorApplication-playModeStateChanged.html
is this what you're talking about?
The typical (often recommended) use case for SOs however is to treat them as containers for immutable data, not even holding any internal non-primitive state
I'm using the gitignore file but I'm unsure how do I have it ignore the ArtifactDB file in Libary? I put it in the right place with the proper format to boot:
okay, so i'll have to change my solution then. i wanted to cache some data on the scriptable object but that'll have to move somewhere else
It has to be called .gitignore
Oh
So if ArtifactDB file is being tracked already, do I need to remake the whole project again?
Cus I did what you asked, same problem like usual.
Just delete the .git folder and init again with a correct ignore file
Ok!
Alternatively close unity, delete the library folder, commit, then reopen Unity
Let me try that one. Seems easier.
if you have committed the library folder once (by accident) your git repository is however full or useless changes, if you cannot reset the repository to a state before that commit, it’s best to recreate it
Deleted the Library Folder.
Git still thinks I have the Library. I think I gotta clear the history.
are you willing to lose your commit history
No
because you should probably just delete the .git folder and reinit the repo at this point
Ok
Is that a bad idea if I loose it?
Mostly as I'm worried it'll delete the main project as well.
Its my first time uploading it to git so nothing much has changed yet.
you won't lose your files if you do, but if you have a history of commits, you would lose that
you could always just clone the project, then do whatever you need like try remaking the repo
Ok
tho do you really have anything in the git history? sounds like you just started using it
just go to the folder where your project is (Assets, ProjectSettings, etc.), turn on hidden files, and delete the .git folder
you can reinitialize the repo from there
Any notes with the last two?
you already have a git ignore
unless you're open sourcing your project, it's fine to leave license as none
i haven't touched a git gui in forever so idk if this is going to commit everything automatically
also another question: is using a scriptableobject as the key in a dictionary a good idea or nah
Do you even have a proper gitignore file for Unity?
Yes:
Is there any reason why my FPS portal-like physics based puzzle platformer SHOULD NOT have variable jump height?
The player builds bridges to solve puzzles and get to the end of a level/chamber. The bridge building is the core mechanic. I like the idea of letting the player the decide what type of jump they want to preform for the situation at hand. Keep in mind HOW you traverse the level/movement is a huge part of the game!
All this and I'm still not 100% certain.
If I did add variable jump height how would you teach and reinforce this mechanic to the player with an invisible tutorial?
Hello, i have a question.
Is there a way to capture the desktop audio? i need to capture current desktop audio and send it via WebRTC for my screen sharing system?
just open the scene you had open last
deleting Library deletes your current editor state
whats the history tab got
Make changes, select them, click on the bottom left
Ok
okay then yeah commit when you make changes
So just do some random code (//random) and it'll automatically commit?
no. git will detect changes and allow you to select what changes to include in the commit. after that you may commit
Ok
I changed a bit of the coding to try and have Github commit but it doesn't respond.
Lemme try something
Then the changed files are not in the local workspace/repository or are ignored.
I have a hunch that this might cause a problem:
Its a bit scuffed, but it works. @cosmic rain @twin egret @cold parrot https://github.com/Etoiel/TenWindowsGame
Bonus when after I booted it up on Unity:
So its all good, thanks everyone!
Glad you solved it, but I'd recommend not having your project on desktop. That's inviting all kinds of problems in the future.
Hi all, I'm generating meshes procedurally, I want to apply a different texture which would represent a pavewalk on the red parts I drew in the image. I have to cut the mesh, but I'm wondering what is the best way to do this, do I have to create 2 different meshes?
Heya, got a question.
Anyone has an idea how to edit the autogenerated Scripts?
Namely the Entities C# scripts, which don't appear in the Data/Resources folder
C:\Program Files\Unity\Hub\Editor<editor version>\Editor\Data\Resources\ScriptTemplates
this sounds more like something for #📲┃ui-ux than a code chanel
i ask my quetion there ?
yes
That's what I'm saying, the Entities scripts (baker, system, etc') aren't there.
you should use #🔎┃find-a-channel BEFORE asking your questions
I'm looking to change the baker template
then they may well be in the global package cache for the package
Any idea where that might be?
A google search away
https://docs.unity3d.com/Manual/upm-cache.html
Thank you
btw these are not code questions and do not belong in a code channel
Got it
hello my audio source keeps on looping every frame, https://www.toptal.com/developers/hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I want to write modules which are engine independent. For example, I would make image filters. They would use Image abstract class I would make. It would have setpixel and getpixel abstract methods. I would use adapter pattern yo make unity, godot, monogame APIs fit into my hierarchy. Each Implementation of my abstract image class would have constructor injected API texture class with pixel read write access. UnityImage will have constructor injected UnityEngine.Texture2D texture; and will inherit my abstract class and I would implement setpixel, getpixel by saying texture.getpixel(x, y). Similar approach would be used to make GodotImage and MonogameImage implementations of my abstract class. This is common practice in industry to use adapter pattern to make different APIs fit into same abstraction and be able to swap implementations.
I just wonder what is best way to write modules (nuget, dll or something else) which is supported by all engines. I initially wanted to use nuget since it enables versioning (different versions of project use different version of module/library). I really don't want to use git submodules for versioning because they are extremely confusing when trying to merge, resolve merge conflict, update. I read somewhere that godot doesn't support nuget but they probably support adding dll (or so files since I am on ubuntu) files to some directory. Do all engines/frameworks support .dll (.so)? Is it easy to setup? What is best way of versioning those dynamic libraries? Do they have good performance? I would typically make git repo for that classlib with .net standard 2.0/2.1 so unity doesnt complain and make a bunch of versions/commits of that library. But that may cause dll hell where different dll files have same name and I don't know which version they are. How should I go with thid dll modular approach?
definitely dll
all engines that support C# code should support DLL yeah
and ones that don't support C# code probably still support DLLs in one way or another (untested, but DLLs are a universal programming thing, so I have to assume it's fully working universally)
yes DLLs have good performance. Nuget is best for distribution, others are suboptimal
DLL hell is easy to get in yeah. Plus it can be annoying for devs that want to use and potentially extend them, so maybe you should consider packing your whole engine in a single DLL
yeah seems even unreal supports dll files: https://docs.unrealengine.com/4.27/en-US/ProductionPipelines/BuildTools/UnrealBuildTool/ThirdPartyLibraries/
Should I make some bash script which reads first row of commit message and appends it to dll name? "ImageFilters - added basic filters for rotating.dll" would give me ability to know which version is which since different dll versions would have different names. In csproj of that classlib used to make ImageFilters.dll, I would add line which automatically executes bash script for dll renaming.
DLL are universally supported regardless of engine
You can also support C and C++ DLLs in your application by using the extern keyword and loading them into your application
The thing you should worry about is compatibility between .NET versions in your DLL. Generally you want to target a .NET Standard version if you want others to use your library
If all engines somehow supported nuget, what would you suggest as easiest solution regarding performance, versioning and ease of use?
For example, Unity supports the latest .NET standard version
But often people use some .NET version like .NET 8 and Unity does not support that
So instead you should also compile for .NET standard if you want to support Unity. You can specify multiple target versions in your .csproj file
And I believe Godot supports .NET 8 just fine but I don't remember for sure
I didn't say they support Nuget
Nuget is not a thing you support
Nuget is a general package manager for .NET, but you don't use it with Unity because Unity only allows very specific versions and generally they would need to implement some feature for Unity
That's why Unity doesn't use Nuget but instead has its own package manager
You can "support" nuget but there is no guarantee the dll you download from it works
So anyway
you can set a material index per vertex and just have multiple materials on the renderer
If you plan on making "general modules" for anything, you should target specific versions so that anybody can use it. .NET Standard, maybe much older versions. You can use processor directives to compile code specific to a version if older versions are not supported.
And considering it's not related to Unity you upload these to Nuget
As for performance, this makes no sense. Nuget has nothing to do with performance. It's up to you to write good code that has good performance
What about using static linking? Is it possible in C#? Is it batter way to deal with dependency version hell?
what's static linking now?
no if you wanna get away from it pack everything on a single DLL
as for versioning it's git territory -- nothing to do with anything else really
u might wanna keep a constantly up-to-date public const string version = "0.001beta"; which gets printed upon first initialization if you want.
otherwise organize your branches with release, develop, 0.1, 0.2 etc to keep track of releases -- and only push to develop, only cherry-pick to release from develop, and duplicate branches to version branches before making the DLL
also yeah I can see why that is confusing -- I meant to say there's no good way to do versioned distributions unless you use Nuget -- but it's not really supported anywhere except standard C# applications
Ok C# cannot use static libs I didn't know. I have watched some yt recently and found out that godot supports nuget and that there is some github NugetForUnity repo which enables nuget window to visually add nuget packages. That github is someone's add hoc solution which may or may not work every time but at least there is some way to have nuget in unity
github has option for release pages now that potentially include changelogs & binaries, but nothing beats Nuget -- since it automatically tells you which are up-to-date
yeah there's an Unity asset that allows nuget downloads but what Fused said above stands
Hey there, Im currently having issues with the rigidbody.velocity.magnitude function
im trying to detect, wether or not the Rigidbody (attached to a different GameObject) is moving with a speed != 0
However, this change is only detected, when the Rigidbody comes in contact with another Rigidbody (ie. comes in contact with an enemy)
After some fiddling around, I noticed that this weird behaviour only occurs, when all 3 axes of the Rigidbody´s rotation are frozen, if at least one of the axes is not frozen, the code works normally
Could anyone help me figure out how I can make this work with all 3 axes frozen?
Code:
using System.Collections.Generic;
using UnityEngine;
public class animationStateControlle : MonoBehaviour
{
Animator animator;
[SerializeField] Rigidbody rb;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (rb.velocity.magnitude > 0)
{
print("Change detected");
}
}
}```
How are you moving the body
If you're not moving it via physics then the Rigidbody isn't going to have a velocity
how would i get the number of lines in a text file?
string[] lines = File.ReadAllLines(fileName);
int count = lines.Length;
Count the number of newline characters and add 1
i assign the scrollbar right, but when i put it into the prefabs it dis assigns, so then theres no scrollbar assigned? why is this
Prefabs can't reference objects in scenes
oh so how do i assign it someway?
(assets in general can't reference objects in scenes)
Assign it at runtime to the instance after you Instantiate
how? idk how to access the instance from the hierarchy
how do i count newline characters?
you read every character in the file, compare to newline and increment a count when you hit one
Instantiate returns the instance it creates
You don't need to do anything with the hierarchy
With an int
ohhh, that makes sense
yeah, im not moving the body via the rigidbody component
then all bets are off
but thx for the help mate!
how should someone know what it is on YOUR specific project 
Profile and find out.
also this seems unrelated to unity
?this is unity help coding channel
your post is not related to that
my bad, it's not clear that this scripting section is only for asking help with unity as nothing implied this was unity specific scripting questions in the read me channel. removed, sorry for trying to share
The entire server is for unity only. They don't really specify that for the channels because it is just in the name
Yeah, that's why I shared a details about a setup I use to make coding my Unity games easier and I put it in this channel because it is titled as code-general which I understood to be related to writing code and using Unity. What @rigid island said is that this is only for asking help questions, not sharing resources.
Thanks for joining in on the unnecessary clarification though about what the Unity discord is meant for.
You understood wrong. It was clearly very necessary
clearly
I have a plane here and a perspective camera at a downward 45 degree angle. I want to right click + drag and be able to move the camera along the plane. Any tips?
Plane.Raycast to get the world space positions of the mouse. Then it's just a matter of moving the camera by the same offset in world space that the mouse moves
Ya I did something similar and upon right click the camera jerks.
private Vector3 _origin;
private Vector3 _difference;
private Plane plane = new Plane(Vector3.up, Vector3.zero);
private void LateUpdate()
{
if (Input.GetMouseButtonDown(1))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
plane.Raycast(ray, out var distance);
_origin = ray.origin + (ray.direction * distance);
}
if (Input.GetMouseButton(1))
{
var newRay = Camera.main.ScreenPointToRay(Input.mousePosition);
plane.Raycast(newRay, out var newRayDistance);
_difference = newRay.origin + (newRay.direction * newRayDistance);
mainCameraFocus.transform.position = _origin - _difference;
}
}
obligatory cinemachine 😮
I am
I'm moving a target for Cinemachine to smoothly track as opposed to moving the camera itself.
you're using Plane.Raycast incorrectly
Or rather, you're interpreting the results incorrectly
I thought it returned the distance to interception?
_origin = ray.origin + (ray.direction * distance);```
This is wrong, it should be:
```cs
_origin = ray.GetPoint(distance);```
oh wait that's the same actually
sorry
I misread
mainCameraFocus.transform.position = _origin - _difference;```
I don't think this is right
let me check my code for this. I've done this exact thing before
Thanks, appreciate it.
Does this work @dawn nebula ? I couldn't find my code but I tried to rewrite it:
Vector3 _origin;
Vector3 _cameraOrigin;
private void LateUpdate()
{
if (Input.GetMouseButtonDown(1))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
plane.Raycast(ray, out var distance);
_origin = ray.GetPoint(distance);
_cameraOrigin = mainCameraFocus.transform.position;
}
if (Input.GetMouseButton(1))
{
var newRay = Camera.main.ScreenPointToRay(Input.mousePosition);
plane.Raycast(newRay, out var newRayDistance);
Vector3 newMousePos = newRay.GetPoint(newRayDistance);
Vector3 diff = _origin - newMousePos;
mainCameraFocus.transform.position = _cameraOrigin + diff;
}
}```
Yep, thanks man.
in unity how do i detect the object that hit something? all i can find it the object that was hit, i wanna tp the plr or the object that hit the other object to somewhere
Debug.Log($"{collision.gameObject.name}");```
yeah that tells me the object that was hit, not the object that hit it
It tells you the other object
ohh
this object is just this.gameObject
whats the $ for?
Itd be quite useless if it only told u what the current object was
i want the collison to tp the player if the collision was hit tho
which object is this script on
a tp script
then the player is collision.gameObject
or you might want collision.collider or collision.rigidbody or collision.transform
depending on your needs
The docs will tell you the difference between all of these https://docs.unity3d.com/ScriptReference/Collision.html
so then how would i detect if the plr hit the part to then do smth
check if the object is a player
then do the thing
That might mean checking its tag, or checking if it has a specific component on it
for example:
if (collision.gameObject.TryGetComponent(out Player p)) {
p.Teleport(someLocation);
}```
so where do i now put the function? how do i connect it so it fires
In OnCollisionEnter of course..?
it isnt doing anythig tho
Start with this
without any if statements
to make sure it's even running
If it's not running at all, you didn't set up the objects correctly for OnCollisionEnter
nothing
Ok so - show the two objects that are colliding
show their inspectors
ignore the plr transform its not needed
and the player?
its multiplr so i cant just have 1 player
Can you show the inspector for the player too?
its why i wanna detect
I didn't say anything about how many players you have
yeah but if i connect the player to that transform, it would teleport everyone right?
I just want to see the inspector for the player object that you expect to collide with this teleporter
Id didn't say anything about doing that
I just want to see its inspector please
Ok you are using a CharacterController.
CharacterController does not trigger OnCollisionEnter
oh
For that you need to use this https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html
and I think that code can only be on the CC side
oh
i dont get it
what don't you get? You have been provided with an example of how to do what you need
You should heavily reconsider if you're actually doing multiplayer since you clearly arent familiar with unity basics
That is a different method you must use instead of OnCollisionEnter. Simple as that 🤷♂️
mines a character controller not a ridgid body
Yeah what do you think that link is for
rigid bodys
Where did you get that idea?
bc it assigns it Rigidbody body = hit.collider.attachedRigidbody;
It's example code
It's checking if the other thing has a Rigidbody
It's also completely not important
It's just example code
CharacterController.OnControllerColliderHit
figured
is that how its written in the example documentation ?
i think
wdym you "think" its literally there wirtten in text
what does it say
the same as what i put
so what do you think the answer is here
theres no "hit" there
what for
well im confused bc u sent an atricle of what is what but hit isnt there so idk what hit is gonna be used for
hit is the variable name for the data next to it, it can be anything.. the name is not relevant
do you know what Method parameters are?
I made a Debug.Log check for the brake/reverse input. If the car is stationary or moving backwards, and i hold brake, the car moves backwards and the message keeps getting sent as long as i am holding brake, as expected. but if the car is moving forward and i hold brake, the message is only sent once and the car doesn't brake.
https://gist.github.com/Winter-r/447c521d359129f2586cc6ae923b2dbd
you dont have to upload to gist to share code, use site from !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hit is a variable name. You could call it foo or poop or rainbow for all that it matters. What you called hit is a ControllerColliderHit. So the docs that navarone sent are what you need to look at.
Of course it will not have the randomly chosen variable name in the docs.
Why spawn areas rotating
how should we know? Presumably due to your code.
wait i have another issue, idk wtf happened but by is my character rotating like this now
Looks like your character isnt centered and you're rotating a parent object. But im just guessing since you didnt show relevant code. Also stuff like this really belongs in #💻┃code-beginner
your code is pretty explicitly rotating the spawn areas randomly
GameObject Sheep = Instantiate(sheep, SpawnPosition, transform.rotation = RandomRotation);```
transform.rotation = RandomRotation < this rotates the object the script is attached to
i.e. the spawn area
To spawn an object with a random rotation you would just do:
GameObject Sheep = Instantiate(sheep, SpawnPosition, RandomRotation);```
You have the extra `transform.rotation = ` in there which is causing your problem
Why not just MonoBehaviour.Update?
public abstract class MBPool<T> where T : MonoBehaviour, IPoolEntity {
protected Queue<T> pool = new Queue<T>();
protected Transform poolParent;
public virtual void Initialize(int maxAmount, T prefab) {
poolParent = new GameObject($"{typeof(T).Name} pool").transform;
for (int i = 0; i < maxAmount; i++) {
var newObj = UnityEngine.Object.Instantiate(prefab, poolParent);
newObj.OnSpawn += () => OnSpawn(newObj);
newObj.OnDespawn += () => OnDespawn(newObj);
OnEnqueue(newObj, i);
pool.Enqueue(newObj);
}
}
public virtual T GetNew() {
if (pool.Count == 0) { return null; }
var obj = pool.Dequeue();
obj.OnSpawn?.Invoke();
return obj;
}
protected virtual void OnEnqueue(T poolObj, int i) => poolObj.gameObject.SetActive(false);
protected virtual void OnSpawn(T poolObj) => poolObj.gameObject.SetActive(true);
protected virtual void OnDespawn(T poolObj) {
poolObj.gameObject.SetActive(false);
pool.Enqueue(poolObj);
}
}
this doesn't handle automatically collecting despawned objects, but sounds like better architecture than having a manager for despawning objects
it's for a demo project I've done some years ago, here's an example usage for reference -- quite simple: https://github.com/Lyrcaxis/Hack-and-awesome/blob/main/Assets/Scripts/Utilities/EnemyPool.cs
(simple I mean the usage 😛 the contents may not be that simple lol)
np!
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/object-pooling/
The unity multiplayer docs also have a good setup for object pooling. You just change the networking stuff to like GameObject or Component. Whatever you want
Though regardless if you want to automatically return objects to the pool then ideally you have some timer, either on the pooled object or the pool itself keeps track of them all in a separate list
You can skip a lot of the beginning since it's very specific to unitys networking for game objects (NGO)
bro
nobody answer me
I mean, what are you expecting as an answer? The question is so vague.
Make a panel and child a text component and... write some text? I dunno because you do not describe what you actually want at all.
Go to the #📲┃ui-ux channel and write a WAAAAAAAAAAAAAAAAAAAAYY more descriptive question.
With details
And images if necessary
thanks
🌹
this thanks came with an engagement proposal 😆
bro i sent photo
what is the problem
i want to add it in my game
but idk
just this
instead of being lazy why not search it on youtube
@glossy isle 😂 dude you're really funny!
Here's a little tutorial I put together on how to create a text window that displays messages. In this video I show you how to create a script that runs the text window, chat input and messages sent to the text window. This is my first unity tutorial so if there is something that I could clarify or perhaps improve on in the future, feel free to ...
why 😂
when i search i get msg box in pc windows
thanks 🌹
I mean -- what you posted is full-fledged multiplayer chatbox, it's unlikely to get it done simply by following a tutorial 😅
also the way you posted it was funny as heck lol
There is a picture, but the words are even more vague then before. Tell us what you tried so far and why it didn't work
why not actually adding Unity to the search terms..
i search but i can get response
What?
😮 oo . i don't know bro
bot => but
That does not make it any more clear
what does "I can get response" mean?
i can't get best answer
Incorrect
wrong
where do you think we get our answers from most of the time?
I don't do DMs sorry
Hello everyone,I have been having a problem with a small project im working which is the top,bottom,right and left faces of this randomly generated cubes show up with distorted textures
I have been tinkering with it and I think I have probably made a mistake on how I make the triangles for the faces of how I give/assign the UVs
Here is some screenshots with how it looks in the editor and the code behind it
Could it be any of this 2?
For my game, I want to create an upgrade system in which I can change certain things about a tower and those changes will apply when i call Upgrade on a Monobehaviour, like how you can have overrides on a prefab variant. However, I dont want to reinstantiate the gameobject, is there a way to make it so that it will store the overrides of a prefab variant (or a functionally equivalent system), and allow me to change that based on changes when I upgrade?
I am working on a vampire survivors like game. In the game, if you have a pistol in inventory, you start automatically shooting. If you have two pistols in the inventory, there should be two instances of these auto shots but I was not sure how to best implement this. Creating an actual new instance of the class wont work since its monobehavior.
You can AddComponent if that's what you want, but I'd probably not use monobehaviour for these objects.
You could do something similar to what LOD groups do. Have every single variant under a single gameobject then only set the one you want active.
okay yea addcomponent would be a way to go about it, thanks. How would you instantiate the bullets without monobehavior?
Instantiate is just a method, you dont have to call it from a monobehaviour
another problem is rendering to texture
Starting a new project and marked my camera and player as DontDestroyOnLoad. In my second scene I have another player and camera object I use for building and testing, but when I play through the first scene and load the second, I was expecting to have duplicates (those in the second scene + the ones marked DND from the first scene)
But that's not happening. It looks like the DND gameobjects from the first scene are overwriting the gameObjects that I placed in the second scene
That's ...neat, but unexpected?
Does it work automatically that way now?
Of course not, unity doesnt care if you have duplicate of a prefab. You must be destroying one of them at some point if they're not there in the hierarchy
so weird. thanks for the confirmation. I'll go find out where it's de-duping
I'm gonna make a wild guess and say its in the same area you use DDOL probably because you made the player a singleton and destroy all other instances
It's something you learn here after some time of helping people.
We can also see your project with a third eye and read your thoughts.
👻 the error is on line 15
That's a really legit guess given that singleton code is generally up top
hey so i need help making a game, im struggling to put my ideas into it and need help, i know it kinda seems a little jumpy but i could really use the help.
i have taken classes on coding with unity before but need some help with it
What's the actual question?
If you ask a specific question, someone may help
#854851968446365696
yeah, im just trying to put it into words
So basically, i want a system where if the player hits the enemy every time the enemy and the player go up in the air, To put it like this
One hit would just launch the enemy backwords
Two hits would send you and the enemy upwords a little bit and then if their is no other button press, you both fall back down
Three hits would launch both of you up and the last hit would knock the eneny back
So knockback
And what have you found online when you looked?
kind of
lemme finish the text cause i accedently pressed enter early before i could finish what i was writing
lemme make a diagram
Sounds simple enough if you keep track of the number of hits and apply force/velocity/movement accordingly.
ive tried something like that
private float distance;
EnemyBehavior enemyBehavior;
PlayerBehavior playerBehavior;
EnemyAI enemyAI;
public bool CanAttack;
public bool DoubleAttack;
private float LastClickTime;
private const float DOUBLE_CLICK_TIME = .5f;
void Start()
{
enemyBehavior = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyBehavior>();
playerBehavior = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerBehavior>();
enemyAI = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyAI>();
}
// Update is called once per frame
void Update()
{
distance = Vector2.Distance(transform.position, Enemy.transform.position);
if (distance <= 2)
{
CanAttack = true;
if (Input.GetKeyDown(KeyCode.P))
{
if (PlatformGameManager._playerStamina.Stamina > 0)
{
Debug.Log("Hit");
float timeSinceLastClick = Time.time - LastClickTime;
if (timeSinceLastClick <= DOUBLE_CLICK_TIME)
{
enemyAI.EnemyLaunchUp();
playerBehavior.PlayerLaunchUp();
enemyBehavior.EnemyTakeDmg(10);
playerBehavior.PlayerUseStamina(20);
DoubleAttack = true;
}
else
{
enemyAI.LaunchBack();
enemyBehavior.EnemyTakeDmg(5);
playerBehavior.PlayerUseStamina(10);
DoubleAttack = false;
}
LastClickTime = Time.time;
}
}
}
else
{
CanAttack = false;
}
} ```
Which unity extension do I use in visual studio code?
!vscode
the problem i have with this code is 1, it doesn't launch up correctly and 2, it dosent go in the right direction
Did you make any attempts at debugging it?
yes
And? What did you discover?
Debugging means finding the issue cause and potential fixes via various techniques, like logging, drawing debug info/gizmos, or stepping through the code with a debugger. If you didn't discover anything, then your debugging failed.
Or rather, you never completed the debugging.
How so?
It might cause issues during the build due to file access rights.
Ideally, put your project close to the disk root.
disk root?
C:/ is a disk root
D:/ is too
So something like C:/UnityProjects is always preferable
Ah
can I make it so that a certain ScriptableObject only appears when I rightclick a prefab, just like a prefab variant?
using UnityEngine;
[CreateAssetMenu(fileName = "New UpgradeAsset", menuName = "???")]
public class UpgradeAsset : ScriptableObject
{
public GameObject originalPrefab;
}
smth like that
and it stores the prefab I created it from in originalPrefab?
Im not sure ive seen this use case before, ScriptableObjects are files that are stored in your project, a prefab can reference that file, though I dont see how restricting creating it to a specific prefab would help if it would create a file in your project that anything can reference anyway? Through the attribute alone there is no way to do that, AFAIK it would likely involve a custom editor window or editor script - what might be the end goal of such a system? Why is this specific scriptable object unique to only one specific prefab in your project?
Well basicaslly
i want to create a very flexible upgrade system for prefabs
where I can change like everything about them, similair to how a prefab variant works. Right now, ive been trying to figure out how to hijack prefab variants for htis use case, but I was exploring the possibility of creating my own custom asset to work better.
Ah I see, there are likely other ways but one that comes to mind is possibly using generics, interfaces and inheritance to create "variants" with different logic and public variables, it could help to maybe plot out a set of what your variants could look like, what needs to change between them and how you intend to use or reference those changes, for example you could use a serialization library like Newtonsoft JSON and use text files instead of ScriptableObjects, depending on the depth of your system and how you intend to use them, both would have a different process for actually populating and making copies of your data though (although a ScriptableObject is also basically a fancy YAML text file that Unity serializes)
hey if there are multiple references to the same instance of a custom non-unityobject on multiple classes that needs to be serialized is it a better idea to use serializefield or serializereference
Depends on the behavior you want. Is it important that they all reference exactly the same object?
If not, it doesn't really matter. SerializeReference may give you smaller data size I suppose
yeah i expect to have 6+ different things referencing the same object
https://docs.unity3d.com/ScriptReference/SerializeReference.html
You might want to serialize as a reference rather than a value when:
You want multiple references to the same instance of a custom serializable class.
I feel like the answer is SctiptableObject... or it doesn't matter... but oh well 🤷♂️
Hello there guys! How to disable creation and uploading symbols.zip for Android build?
i did some research and found almost nothing about it
It's in the build settings, no? There's a dropdown for them symbols
yeah, i forgot to say my build starts through command line or something like this, and idk where the person who responsible for this solution
is it an automatic build thing? it still probably uses whatever settings the project is with, so you can change from the same place and push 🤷♂️
There is EditorUserBuildSettings.androidCreateSymbols if you need to change it from code, I guess 🤷♂️
There's probably a script in the Unity project being invoked by the build script. Check to make sure if it's overriding any settings
oh thanks, ill check both options
right, i found one, but no code working with symbols in there unfortunately
anyway thanks
How I can build game with script?
I mean, when I run.exe file, and in the game I press the button called "Build", it should be build game for windows
if you mean from C# script then it should be like BuildPipeline.BuildPlayer()
using UnityEngine;
public class BuildScript
{
public static void BuildGame()
{
string[] scenes = { "Assets/Scenes/Scene1.unity" };
string buildPath = "C:\\Users\\Admin\\Desktop\\MyGame.exe";
BuildPipeline.BuildPlayer(scenes, buildPath, BuildTarget.StandaloneWindows64, BuildOptions.None);
}
}
Like this?
yeah, doesn't it work?)
Here's other script:
using UnityEngine.UI;
public class BuildButton : MonoBehaviour
{
public Button buildButton;
void Start()
{
buildButton.onClick.AddListener(OnBuildButtonClicked);
}
void OnBuildButtonClicked()
{
#if UNITY_EDITOR
BuildScript.BuildGame();
#endif
}
}
oh right, it's only from editor so i think you cant run it in the game)
Can I use resources folder? 
Yeah, I'm dumbass
dont remember
obviously the build script should be in editor folder or entirely #if UNITY_EDITOR'd
So, it's woking only in editor?
I mean... it's the editor that is building the game... where else would you want it?
sorry but i really dont remember this)) try to google it or ask gpt
I want to build the game INSIDE the game
you can't... but also am curoious for the use-case
you may run like bash script or kinda from your game
Only editor can build. You can tell your editor install to start a build from a game though.
Bat File?
I have to run it through a script?
np
But I still have one more little question
You can start the process from C# too
i hope it works)
What if this game is on Android?
oh it may be significantly harder to run if not even imposible)
Then you first need to connect to a device that is capable of running the editor
actually imposible))) it's android, you dont have an editor on a device
☝️
did we discuss the use-case?
this seems super weird to me... I'd think there's a better way of doing whatever, unless it's really super specific
no, still very interesting))
¯_(ツ)_/¯
This doesnt really look related to what you're asking above. You should say what the actual use case for this is, what game mechanic are you trying to create?
Game building system
i really dont feel like playing 20 questions to get more information. It sounds like you're trying to make an app which can create games? You simply arent gonna be building a game from an android app.
hey, when i want to restart my game in singleplayer i just call SceneManager load scene and it restart the game, but i unity netcode when i want to do the same thing it doesnt restart the game when using Networkmanager.SceneManager.Load. What am i doint wrong?
Yes
#archived-networking or theres an unity multiplayer server pinned in there
How can I make a randomly wandering animal on the map in Unity?
pick random point - go to it, when you reach it - restart the process
please do not cross post, delete from here and stick to #💻┃code-beginner
Already
Hi All, I was wondering if anyone knew the best way to render meshes with multiple materials using Graphics.DrawMesh and if it is more performant to use DrawMesh or RenderMesh?
guys help me in this one i try to build app then this error comes up
Not a code question, please do not cross post
if (validVectors.Count > 0)
{
Vector3 averageDirection = Vector3.zero;
foreach (var vector in validVectors)
{
averageDirection += vector;
}
averageDirection /= validVectors.Count;
vectorField[current] = averageDirection.normalized;
}```
right now im calculating the vector of my resistance field by taking the avarage. but it should point into the avarage of the lowest resistances. how could i make the lower resistances weigh more than the higher ones?
How about something like that ?
float average = 0;
var elementWeightNormalizeds = elements.normalizeWeight();
foreach element in elementWeightNormalizeds
average += element.value * element.weight
[(0.5,0.7), (3, 2), (1, 1.5)]
float weightSum = 0.5 + 3 + 1 = 4.5
[(0.11,0.7), (0.66, 2), (0.22, 1.5)]
average = 0.11 * 0.7 + 0.66 * 2 + 0.22 * 1.5 = 1.727
A more performant way would be:
average = (0.5 / 4.5) * 0.7 + (3 / 4.5) * 2 + (1 / 4.5) * 1.5 = 1.727
fellas I think I mistyped something
i'm trying to understand what you wrote but im having trouble wrapping my head around it😅
what is gameRunner and why are you trying to assign a class to it 🤔
classes are just blueprints to objects
gamerunner is the static instance of this class (GameRunner)
I mistyped "this" and it corrected to "ThaiBuddhistCalendar" which I thought was hilarious
thanks ill check that out
If I'm to understand this correctly, if I'd like to use Scriptable Objects to save data for my character creator.. would it be best if the data while it's 'hot/live' is kept as a JSON in memory - then once the character is finished, create a new instance of the SO we'd based this JSON off of initially, populate it with data from this JSON, then save this new SO asset to the disk?
Sorry if I'm wording it vaguely lmao, just want to know if this is how it should be done
As long it is not runtime save.
ScriptableObject is not made to save data from runtime.
Okay, so it's more for when you have static data you'd like to 'plug in'
Immutable data.
yes, if you make that data runtime-mutable, you will shoot yourself in the foot.
Would using it for a game save then, where I'm instantiating a new SO asset, not be recommended?
Yo
no, not recommended
Can I make a ticket?
no
Okay
you can use an SO as a reference to, or container for, a configuration for a game-save/load mechanism
you can even put a reference to that game state which you want to save/load into your SO if you really want that.
but that would be more or less the same as a global static variable, and that generally is not a great thing to have.
Oh okay, that makes sense!
regadless many simple games use a global game state object successfully. Its up to you how to make that accessible and how to mitigate the issues it brings. Piping it through an SO is one of the options,
So I could use the structure of that SO and have my game saves as actual JSONs without a hitch in the future as my project gets increasingly complex? (lmao open-ended question)
its irrelevant that its an SO
you have a global state object and everything in your game will be coupled to that object's structure
Trying to understand this. A class would serve the exact same purpose and structure, right?
if you expect a complex data model and worry about maintainability, you could inject objects only with a small portion of that gamestate (through an interface), effectively reducing the surface area of the coupling
yes
a SO is just an instance of a class that is automatically created on application start and gets its public (serializable) fields filled with static configuration you defined when editing the game in the unity editor.
an SO solves the problem of "where do i put my static configuration" for unity projects
you could also look at them as custom asset types
So, having the options as an SO itself would be pointless since we're going to be messing with it at runtime anyways?
Braining: If I'm to have a bunch of SOs in a folder, let's say it's uhh.. Graphics Presets. We're never going to change those at runtime, and we can reference them easily like they're just a convenient data container. Like any other static object. However I choose to store my actually runtime-modifiable settings data, it's all good for me to reference those SO assets?
I hope I understand now what they're actually for. I was using them like this before, but got caught up in figuring out how to save a bunch of characters. I'm going to check out custom assets now based on the advice.
Unity documentation is shit. what do I use to raycast from a position & direction in worldspace, to hit a canvas, in worldspace.
What are you trying to achieve exactly?
performing a raycast yourself is not necessarily the right approach
Physics raycast (probably what you were looking at) is only for physics colliders, not UI.
Physics.Raycast
and if you are really feeling funky you could put a collider on your ui
I'm trying to raycast from a position and direction in worldspace, to see if that ray hits a canvas within a set distance.
I'm aware physics raycast doesn't hit it. I'm trying to figure out what raycast does hit it.
why are you trying to raycast though
what's the actual goal
what are you trying to achieve.
There's a better way to do it probably
To know if the ray is hitting a canvas. Internal logic. XR shit.
normal raycast should hit it if the canvas has a collider
This is what the graphic raycaster is for
but also - generally you would just use the event system directly
if you're trying to do UI interaction
I'm not trying to do interaction, I'm trying to see if an arbitrary point in space, with an arbitrary direction, and an aribtrary distance, would cast a ray that hits a UI element, whether that UI element is on screen or not does not matter in the least. it's not for interaction. it is just for seeing if a point would hit a canvas.
I do not know if this is here that I have to ask some questions for help but here an "issue" I met by attempting curiosity test.
It's a little question that may take only a minute to answer but I can't find the answer whether by using Unity Docs, GPT or VS Intellisence built-in feature :
// Enable the input actions
playerInputActions.Test.Enable();
// Subscribe to the different phases of the action
playerInputActions.Test.Press.started += OnPress;
playerInputActions.Test.Press.performed += OnPress;
playerInputActions.Test.Press.canceled += OnPress;
I have this code, is it possible to compact all of those subscription to my action phases ? Like is there a keyword allowing me to trigger OnPress() whenever it's started, performed or canceled ? All of that without having to have three subscription so.
no but you could write a quick helper function:
public static void SubscribeAll(InputAction a, Action<InputAction.CallbackContext> listener) {
a.started += listener;
a.performed += listener;
a.canceled += listener;
}```
Graphic Raycaster lives on the canvas, as opposed to an arbitrary point, right?
Then use it as such:
SubscribeAll(playerInputActions.Test.Press, Onpress);```
Yes it lives on the canvas
and needs to have the event camera assigned
Hé, that isn't that dumb ! I have a question though, why is there "Action<InputAction.CallbackContext>" for the listener ? I'm supposed to only use the name of the method so for instance, I'll use "OnPress", no ? Why using CallbackContext then ?
Action<InputAction.CallbackContext> is the delegate type for all those events already
I'm not really sure I understand the question.
Yes but why using it for the method that is called whenever the context is the right one ?
I don't undestand what this question means
So there's seriously no way without putting a camera on the arbitrary points I want to check for UI? Unless the camera doesn't actually do anything, the implication is that it wouldn't work if the camera was for example pointing in a completely unrelated direction, so I can't just reuse the main one.
what is the method signature of Onpress?
Why using Action<InputAction.CallbackContext> to talk about the "Listener" while the "Listener" is basically a method I want to call ?
It's the delegate type
it means "a function that takes a InputAction.CallbackContext parameter and returns void"
public void OnPress(InputAction.CallbackContext context) {}
Ah I see
Hmm hmm ?
that's what the delegate type is enforcing
Oh
ok, now do you see the relationship?
Hey is anyone here familiar with OSCQuery for VRC?
I am writing a very simple program in C#, the program is already writtena and works, I've gotten as far as building an OSCQueryService that is recognized by VRC, but I am having trouble understanding the limited documentation and examples available, and I am stuck on the last step of... how do I send my data to VRC?
https://pastebin.com/ncx22VmW
Here is my code, I feel like I'm just one step away from completing this but I cannot figure it out... any help would be greatly appreciated!
and heres a link to the library I am using
https://github.com/vrchat-community/vrc-oscquery-lib/tree/main
So basically, it want to check if the function I'm calling have indeed this paramater ?
You are only allowed to subscribe such functions to those events
Understandable.
See what happens if you try a function without that parameter
it will give you an error
I'ma try
I'm trying to implement leaderboards for android and I don't understand why i'm having so many issues.
Only a few times have I seen the play services banner show at the top of the screen with my user and then it stopped showing up.
I saw the leaderboard ui once, but I can no longer get it to show.
Log output
IntegrationHelper --------------- Google Play Services -------------- IntegrationHelper Google Play Services - VERIFIED Play Services: User is authenticated = False Play Services: Trying to authenticate the user Play Services: User authenticated = True Play Services: Trying to show leaderboard, user authenticated = True
`public class GooglePlayService : IGameCenter
{
public void Initialize()
{
PlayGamesPlatform.DebugLogEnabled = true;
AuthenticateUser();
}
private void AuthenticateUser()
{
if (!IsAuthenticated())
{
Debug.Log("Play Services: Trying to authenticate the user");
// PlayGamesPlatform.Activate(); # calling this makes the call below fail
Social.localUser.Authenticate(OnAuthenticateUserCallback);
}
}
private void OnAuthenticateUserCallback(bool isSuccess)
{
Debug.Log($"Play Services: User authenticated = {isSuccess}");
}
public void ReportScore(int score, string leaderboardId)
{
if (IsAuthenticated())
{
Social.ReportScore(score, leaderboardId, OnScorePostedCallback);
}
else
{
Debug.Log("Play Services: Cannot report score, user not authenticated");
}
}
private void OnScorePostedCallback(bool isSuccess)
{
if (isSuccess)
{
Debug.Log("Play Services: Successfully reported score");
}
else
{
Debug.Log("Play Services: Failed to report score");
}
}
public void ShowLeaderboard(string leaderboardId)
{
Debug.Log($"Play Services: Trying to show leaderboard, user authenticated = {Social.localUser.authenticated}");
Social.ShowLeaderboardUI();
}
public bool IsAuthenticated()
{
var authenticated = Social.localUser.authenticated;
Debug.Log($"Play Services: User is authenticated = {authenticated}");
return authenticated;
}
}`
doesnt show any errors helpful to us
Try restarting unity
I have; same results
Are you able to select anything else in other views
I have 2 enemies with dynamic body types in Rigidbody. When i walk to them i can just move them backwards. I found a solution by making them static when in range. Is there a better way to do this?
!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.
{
Vector2 direction = (player.position - transform.position).normalized;
movement = direction;
isAttacking = false;
rb.bodyType = RigidbodyType2D.Dynamic;
}
else
{
movement = Vector2.zero;
rb.bodyType = RigidbodyType2D.Static;
} ```
post your question in the correct channel
whoops im new
ive got it now
so in my unity asset/plugin I distribute to others I have an xml file that holds material information
The users who download this plugin can add to this xml file
But when I distribute an update and they import the updated package, if they forget to disable the importing of the material xml from the package, all their changes get overwritten and deleted
is there a way around this to disable it automitically if the file already exists?
why not just move the file to a different folder after import?
when the updated package gets imported, itll overwrite it seemingly no matter what resources folder it is in
not if you move the file and delete the original .meta file
but it needs to be loaded through resources.load
so it needs to be in a resources folder, which unity will automatically create a .meta for
you misunderstand me
original in Resources
after import move file to Resources/Loaded
delete original .meta file
unity will create a new .meta for the moved file
then you can check if the Resources/Loaded file exists or not and not overwrite it if it does
include an asset postprocessor script in your package
ohhh!!!
so thisll let me decide during import whether or not to import specifical files?
oh wait no
ok I think I understand
no, it will still import the original into Resources but will allow you to decide what to do with it
ahhh sweet
I wish there were errors. I don’t know what else to add or do.
I have an egg falling from a rotated plane, the plane gameobject is nested inside a gameobject which i rotate the plane with, i am trying to spawn some rocks from a level generator gameobject, the problem i couldnt figure out how to make the spawn position relative to the rotation of the plane.
Any help will be appreciated.
Pick a random coordinate in the local space of the plane
then convert to world space with Vector3 worldSpacePosition = myPlane.transform.TransformPoint(randomLocalPoint);
So I've been using the ol' just ask a question in chatGPT to help me with some of my coding, Are there any setups with good integration with Unity/Rider that people are using these days? I don't mind if it's got a fee associated.
Is there a way to get the Avatar that the AnimationClip was imported with? Editor only way is okay.
I'm trying to make a tool to assign animations to component properties quicker.
Rider can work with unity no problem
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
@spring creek Sorry, I guess my question was a bit unclear, I am using Rider with Unity, I'm referring to AI tools/workflows in that context.
Oh. I dunno if copilot works with rider. But I would guess it does.
I think the proper channel for that kind of question is #1157336089242112090
Honestly, I try to avoid ai since it is 9/10 times garbage, so I don't know
Not a code question. I guess #🏃┃animation makes the most sense. Or #💻┃unity-talk
Not ChatGPT specifically, but you can look into Github Copilot, it has a Rider plugin that supports both inline suggestions and chat. I haven't personally used the chat part, so not sure how good it is, but the inline suggestions are generally pretty good.
Yeah, I was thinking copilot would be the only one. Glad to hear confirmation about support
I was hoping to try something like Cody, but it's not available for Rider
Rider also has AI assistant, which is Jetbrains own
I'm sure there are other extensions as well
Sorry, I am trying to get this in code, should I still move the question to #🏃┃animation?
Maybe those are my only 2 options
They can help with code as well yes. Since it is code, it would be fine in either, but people with more knowledge in animation hang out in the #🏃┃animation channel.
Your choice
I'll try there too, thanks
From what I read copilot is better than AI Assistant
but I also found Cody does have a plugin for Rider
So I will give that a shot
is unitask really as good as it seems to be?
my state doesn t change, and this appears in animation. If i press manual on the bool variable work but automatic don t. I don t un
derstand why.
Imagine
Yes I have been able to. It’s specifically the animator causing me trouble
#🏃┃animation
Show the code
Show the transitions
Hello everyone, I'm looking to achieve some kind of limb removal in a Kenshi like way, do anyone has any insight on propers way to achieve this?
I have untracked changes and I do git reset --hard HEAD but those untracked changes are still there. Internet says that is probably has to do something with line endings and git automatically changing them on checkout or commit. I attached my .gitattributes. Is it incorrect? it doesn't contain "crlf" anywhere. I have empty unity project and don't know when is .gitattributes necessary so I add it from the beginning. Is it wrong practice?
if i set time.timeScale to 0, and then tried to recolor an object, would the object be able to be recolored?
Have you tried it and it didn't work
Were you perhaps using deltaTime to smoothly change it? DeltaTime will of course be 0 when timeScale is 0
i have been trying to change the color of a ui element in my pause menu, but in editor game mode, it keeps its color set to 255, 255, 255, even if the code says that it's color is different
Ok, are you:
A) changing it in Update? Update will not be called when timeScale is 0
B) using deltaTime as I asked?
the change is supposed to be instant, and yes, i am using update
Ok. Update is the reason it is not working
Callbacks like OnClick will still be called 🤷♂️
Could call it BEFORE setting timeScale to 0 too, if possible
but there is other code in update that is being called like normal, and it will still force the value 255, 255, 255 even if i change it in the inspector
Hmm. Then you have other code setting the value somewhere
You should probably just show the code of course
Oh, are you using Color or Color32 in code?
Color
Then it is only values of 0 to 1
If you set it to 1,1,1,1 or anything greater that is the same as 255,255,255,255 in the editor
I tried importing an animation from blender to unity, but the scaling of the animation doesn't work, even though the rotation and the location of the animation works. Anyone know how to fix this?
I have to annoyingly point out that Update will be called when timescale is 0, for future reference 😋
No not at all. I realized that afterwards, but that is a very good thing to point out.
I've been away from unity so long I keep forgetting things
FixedUpdate won't be called as it does require some time passing in the simulation
After some more investigation, this is what I have happening:
UNITY_EDITOR_WIN and UNITY_STANDALONE_WIN both work in scripts written in unity. it determines it to be true
Neither work in a C# file I made in Visual Studio and imported into Unity via DLL. In fact, when I removed those IF statements, it gives me an error saying that it is "Unable to resolve reference 'Windows.Foundation.UniversalApiContract'"
This is probably an issue on VS's end. How can I resolve this error and make Bluetooth LE able to work in Unity?
Neither work in a C# file I made in Visual Studio and imported into Unity via DLL
this is to be expected. those preprocessor directives determine what gets compiled, if those symbols are not defined, then the code they encompass will not be compiled at all into the DLL
Just tested ENABLE_WINMD_SUPPORT and UNITY_WSA, both fail
Just to elaborate a bit further, they're interpreted immediately prior to compilation. They don't exist at the time of compilation nor in build artifacts/output.
I see. how can I fix this and allow Windows API to be run in Unity??
do you have the relevant DLLs in your project?
Yes, they are in my VS project
Not in Unity, because i'm not sure which are the relevant DLLs (I'm trying to use the Windows.Devices.Bluetooth and Windows.Devices.Enumeration) DLLs
@somber nacelle
i am referring to your unity project. do you have the DLLs you are trying to use in your unity project, because if not then naturally you won't be able to use them in your unity project
#if are preprocessor directives, they take effect during compilation, and so they have already taken effect when you compile your code to the .dll.
no, because I don't know which are the relevant dlls (not sure where to find that info after googling for it and failing to find it)
I'm trying to use the Windows.Devices.Bluetooth and Windows.Devices.Enumeration
well you'll need to figure out what DLLs you need and add them to your project
I think it might be system.runtime.dll, system.runtime.windowsruntime.dll, and system.runtime.interopservices.windowsruntime.dll
let me try that, I'll get back to you if it works/doesn't work
It says "unable to resolve reference windows"
let me check how to solve that
yeah there aren't really any ways to fix that online
yeah after adding system.windows it still insists that its unable to resolve reference windows
Adding to where, Unity?
yeah
Just also tried to use the windows api
it says
The type or namespace name Devices does not exist in the namespace Windows
"Unity includes Windows Runtime support for IL2CPP
on Universal Windows Platform
platform."
https://docs.unity3d.com/Manual/IL2CPP-WindowsRuntimeSupport.html
That API is part of the windows sdk, which unity needs to incorporate into the build. And it only does it in UWP builds.
swapping to il2cpp changed nothing (I am on .NET Framework). I keep seeing sources saying that Unity would automaticlly enable UWP when I switch to il2cpp, but it never works. Not sure how to incorporate the windows sdk into the build either. Can you help me enable it?
You have to switch to this build platform if you want to access WinRT APIs.
It's not possible to access in a regular Windows Standalone build.
Using this platform, do I have to build it to run it correctly? or does it work in testing as well?
like if I click the normal unity run button, can it access the functions?
like Windows APi
You have to build. The editor doesn't run under the Windows Runtime.
oh
has unity put the navmesh obstacle code up on github? i need to modify it to support custom polygon shapes
If I have a public abstract class that inherits from MonoBehavior, how might I pass a reference to this class to a subclass that inherits from the abstract class?
There's nothing special about passing such references around, but it's potentially weird that you want to.
What's the use case?
What are you trying to accomplish?
note also that you generally don't deal with references to classes. You are generally dealing with references to instances of a class.
I have a MonoBehavior method that I need to call but can only pull a MonoBehavior reference from a parent class
or, well, if there's another way idk
can you be more specific about what you mean by that?
I really don't get what you mean by this yeah
show the code
if your class derives from MonoBehaviour you needn't do anything special
If you have A : B and B : MonoBehaviour then any reference of type A OR B will also have everything in MonoBehaviour
The MonoBehavior class:
public abstract class Interactable : MonoBehaviour
{
// Message displayed to player when looking at an interactable.
public string promptMessage;
// This function will be called from our player.
public void BaseInteract()
{
Interact();
}
protected virtual void Interact()
{
// We won't have any code written in this function.
// It's a template function to be overridden by subclasses.
}
}
public class EventInspect : Interactable
{
protected override void Interact()
{
Debug.Log("Interaction (" + gameObject.name + ")");
// StartCoroutine(DelayCall);
}
IEnumerator DelayCall()
{
yield return new WaitForSeconds(1.5f);
// stuff to execute with a delay
}
}```
You have a function in your function
ok so what's the problem?
nah just poor indentation
It doesn't like trying to call a MonoBehavior method
What do you mean "it doesn't like" it
what doesn't like it? What did you try and what happened?
it should work just fine, since this inherits from a class that inherits MonoBehaviour (unless you haven't saved both files or something so unity doesn't see that the abstract class inherits MB)
I just need to know what the right syntax is for it
It should be:
StartCoroutine(DelayCall());```
Is that your problem? That has nothing to do with abstract classes or inheritance or anything, you just forgot the ().
The right syntax is uncommenting your StartCoroutine line
that's it?
that's it
it just doesn't need parentheses?
it DOES need parens
it does need them
Opposite
You jumped to a lot of conclusions about inheritance etc 😵💫
Hold and I'll update you, also sorry if I worded it weird
also not super important, but you can start a local method coroutine just fine provided you aren't using the string overload for StartCoroutine
In the future instead of saying "it doesn't like it", sharing the actual code and the actual full error message you get would be a lot more useful and get us to a solution much more quickly.
See I would have, and that was my bad, it's just I had refactored the code a lot afterwards so I no longer have the reproducible broken code
It was probably saying "DelayCall is a method group which is not valid here"
something like that
Ah yeah I'd say so, anyways that worked, thanks a bunch
Is there no way to normalize a Vector2Int?
make into a vector2 then make it back?
yeah ill try that
What do you consider to be normalized? With Vector2, it means the magnitude is 1. But there are only for possible vectors of magnitude 1 with Vector2Int: up, down, left and right.
Ig cause it would not make sense since you will lose precision anyway since its 1 max
Yes, what would the result of normalizing a vector2int with 1,1,0 be?
Never mind, the normal would be the perpendicular/orthogonal (-1,-1)
Wait what?
Also, I just realized I used three values for a v2 🤦♂️
Ah, I had posted something about unit vector prior to the above but deleted - a unity normalized vector would be a unit vector.
I have a quick question, would there be a way to create a mask on a UI using a game object? or something of the likes?
I want to create maybe one big red UI on the screen and mask it with a big circle object centered on my screen, and then when the player zooms out it could like show as a enemy area
or would there be a better way to do it?
Ok, but then they want it as a Vector2Int. So that is the part that I wouldn't understand
Is it not a correct way to make an object move on a speed with the direction being its "forward"?
transform.Translate(new Vector3((float) Math.Cos(transform.eulerAngles.z * (Math.PI / 180) + Math.PI / 2) * speedCurrent * Time.deltaTime, (float) Math.Sin(transform.eulerAngles.z * (Math.PI / 180) + Math.PI / 2) * speedCurrent * Time.deltaTime));```
When I do this, the object does not move forward along its axis
Help is appreciated
Note that the + Math.Pi / 2 is there so I can have the capsule move on its proper axis
Mhhh
or transform.forward, forgot which one it was
I am coming from another language so I may need to get my bearings again 😅
Yeah the normal I want is up
I forgot Unity does that
Yep, so just use that
Well thank you
I just kind of hate that the Euler angles are deg though
It still happens however, when I rotate the object I do it properly do I not?
transform.Rotate(Vector3.forward * -(float)10 * Time.deltaTime);```
It is for a 2D game
transform.Translate(transform.up * speedCurrent * Time.deltaTime);```
My messy math simplified
At this point I am quite confsed
Maybe my camera got messed up
But no though...
Okay let me be more specific, the problem is that the object moves along an axis that rotates faster than when you rotate visually
Say at 0 rad the object moves up, at -Pi/4 the object moves right and at -Pi / 2 the object is already mvoing down
There is a 1:2 ratio so to speak
Translate has a parameter for whether the vector you pass is in world or local space... by default it's local (I think), so you need to adjust the vector you pass, or tell the function it's a world space vector
How curious
you can either do Translate(transform.up, world), or Translate(vector3.up, local)
Ralativity got it
Problem appears to be Solved ✅
the solution was the following
transform.Translate(transform.up * speedCurrent * Time.deltaTime, Space.World); //Space world makes it so the object moves accordingly
Thank you ❤️
That comment is extra weird
Oh?
Space.World makes it so that the vector you pass is a direction in world space
so, yeah, always a good idea to keep in mind what vector is in what coordinate space
Well every engines has its quirks, it is a consideration I failed to have
yeah, yeah, that is true for Translate's params, but the geometry thing is the same for all of them, hence why it's good to keep in mind 😛
I see 😄
this is the code
Hi, I'm currently trying to make a grappling hook esc mechanic. Does someone know of a good tutorial for this?
there are many tutorials on google, but at the end of the day you're gonna need to make it unique for your game
Maybe specify what you actually want. Because right now it just sounds like you wanna move the player in a direction, which isnt really something hard.
if I use the new keyword on something does it get garbage collected or I have to delete it myself?
I want the player to be able to click a point and than be able to swing from that spot and move up and down the rope connected between the player and the grappled spot.
generally in C# you never have to dispose yourself
Whether you use new on it or not isn't really a determinator of that
Things you have to call Destroy on are UnityEngine.Object derived classes.
I don't really get heap and stack
There are also things that are IDisposable that need disposing manually
It has nothing to do with manual cleanup
Classes get allocated on the heap
Structs don't except as members of classes
Heap is basically where memory for reference types is allocated(including whatever data they store in them, even if it's value types). Stack is for value types that are allocated during methods execution, basically in the call stack.
have you tried to create anything related to this? again there are definitely tutorials out there for grappling hooks. The only thing that really changes is how you're moving the character, either by rigidbody, character controller or some kinematic character controller.
I haven't written any code myself yet, since I first wanted to understand what the basics were, but I can for sure give it a try
As I said, do that in #🏃┃animation
Whats the recommended way to modify Unity Packages so they are not treated as cache libraries?
Im modifying a URP shader from Unity repository but it warns changes will be deleted since it belongs to Package Cache
copy it to your assets folder
Its not letting me move it, should i literally copy it?
It should be copied to the packages folder
To turn it into an embedded package
Its on the packages folder in fact
Yeah but actually there or you just mean showing in the unity project window
Oh right
Follow the instructions in the link for copying it from the package cache
Neat, thank you
When it says that cached packages are immutable, when are they reverted exactly?
Whenever it's least convenient in my experience 😂
No idea, probably whenever the unity process detects a change, through file watchers?
im grateful that rider popped a warning saying to watch out when i started editing, it would be catastrophic to lose progress
I think I posted in the wrong channel, anyways, some now how to get the angle difference in relation to pitch direction in Unity using vector3.signedAngle?
SignedAngle is the way to go. Just plug in the appropriate parameters.
I.e. the two angles you want to compare and the normal of the plane on which you want to compare them
if i have an object that has no mesh but has visuals using Graphics API how can i check if its in the camera view to avoid calling draw mesh when not needed
thanks
Can someone help me with writing a script which finds all of the overrides of a Prefab Variant (or a gameobject in prefab form), and applies them to an instance of the base prefab?
Im trying to make an upgrade system which is very flexible, and this is what I want to accomplish, but what I am doing so far seems to not be working.
that sounds like a really, really bad idea
hm. is there a better way to achieve an upgrade system like this?
Do you understand there are going to be conflicts?
you do realise that prefabs can only be modified in the editor not at runtime
the issue is that I WOULD reinstantiate the gameobject for upgrades, but some things like rotation, and other things can reference the tower, (even other upgrades), I want to stay on so it basically needs to keep changes. As such, I sort of want to log every change an upgrade makes and apply those changes on an upgrade and only those changes.
thats not the point - My goal is to basically make a folder which contains prefab variants which are upgrades of the prefab, then loop through and store all of the differences of the prefab varaints in something like a Scriptable Object, and then create a script which allows me to apply those differences to instantiated forms of that prefab at runtime.
You want to be able to update a prefab at runtime?
Why prefab variants instead of just changing yhe data?
how can I get the length of an enum?
Open your browser and type "c# enum length"
I would even create my own asset type for this, but idk how to do that, it just seems to me that a prefab variant holds all of the differences of it automatically, so thats what I aimed to use for this
https://stackoverflow.com/questions/856154/total-number-of-items-defined-in-an-enum#856165
First result, unchecked
sorry
should have goog'd first
Well, it has 600 upvotes, so, probably, checked
As was previously mentioned, modify the data
No, there would be a prefab, it would be instantiated somewhere in the world, and then I would call Upgrade() on a script in it and it would loop through and see if It can apply the changes that a prefab variant had onto the isntantiated gameobject, then do that
ok ok, so how do I store data changes without using a prefab variant?
You... do use a prefab variant
I meant by me haha. Did not open the link
ok that was my idea
Which was fine and doable
alright, i guess im on the right track then
Sure, just don't try to modify the original prefab
that was never the goal lol
and applies them to an instance of the base prefab
That's what you have previously mentioned