#archived-code-general
1 messages · Page 349 of 1
the arrows are seemingly set to global space rather than local so i cant really tell if they are facing the right way
or im not sure what the arrows are even for, doesnt look to be aligned with the foot in the first image
It certainly works as a correction, even though, yes, it seems bad to add some magic values seemingly out of nowhere
i made the arrows local
yep arrows arent pointing correctly
Quaternion.LookRotation points the z axis towards the given direction
wat, Quaternion.Euler has nothing to do with direction
should i just re draw the spline idk if it will work
hey quick question, im working in unity2d and i have a tilemap with a slope on it and want to find the normal vector of the slope using a raycast. The way i have it set up is so the slope tile has a custom physics object where its just a triangle. Is there a way i can get the normal or will i have to do something else? I tried this earlier and basically what happened is when i made a ray it would only return the correct normal if the ray was exactly on top of the edge of the slopes collider
Redraw it or add magic values to correct it, it's your choice
Redrawing it is certainly cleaner
Also I never worked with splines, I'm just taking it as rigging
bro ima just redraw if it dosent work im gonna just go sleep
i am new to splines ....
Alright, good luck
any way thank you both Nanior and Bawsi for helping
does anyone know
Np
Please😁
Eh, it looks normal...?
yea cuz i drew the desired outcome
I think that circlecast does the trick too, if you prefer it
Not sure what you're trying to do there
im trying to shoot a ray at the slope tile and get the normal vector of it
Wouldn't see why it'd not work, except if you by accident start from inside the collider for some reason
yea thats what i was worried about
cuz the normal only is right when its like right on the edge
how do i set up the raycast so it stops when it hits the slope
What does right on the edge mean?
like the edge of the collider
No idea why it doesn't work...
i have the raycast set up so it goes a fixed distance is it possible its ending inside the collider
It doesn't sound like a layermask issue
if so how do i fix this
No, raycast with fixed distance just means that anything further than the distance is ignored
oh
It otherwise behaves like a normal raycast
so how do you explain when i go to a precise distance away from the collider the raycast will work because its hitting the edge of the collider perfectly
it will return the correct normal*
Show me the raycast code
Maybe you're just using the function wrongly
I dont think im using it wrong cuz i drew the same ray with debug.drawray and its working perfectly
forgive me im not on my computer rn so i cant show exact code
Thats alright thanks for trying anyways
The only thing that comes to mind is that the function might have some mistakes, for the rest i don't see how this bug exists whatsoever
Np, bye Neuba
Its just weird cuz the thing only works when im at a very precise distance away from the collider
Bye
Hey, is it possible to restrict specific Brushes on a chosen Tilemap? The Tilemap class is sealed.
Why don't Google Play services work for me?
using GooglePlayGames;
public void Start() {
PlayGamesPlatform.Instance.Authenticate(ProcessAuthentication);
}
internal void ProcessAuthentication(SignInStatus status) {
if (status == SignInStatus.Success) {
// Continue with Play Games Services
} else {
// Disable your integration with Play Games Services or show a login button
// to ask users to sign-in. Clicking it should call
// PlayGamesPlatform.Instance.ManuallyAuthenticate(ProcessAuthentication).
}
}
}
I use this code but absolutely nothing happens in the game
did you take this code from somewhere? your ProcessAuthentication method literally does nothing
I took this code from a tutorial in GitHub from Google Play Services
I thought that this cat allows the player to log into the account and the login window should appear in the game
I need help with my code. I keep getting this illusive Null Reference Error, and I have no idea what it really means nor how to fix it. I tried searching for answers and didn't find anything useful.
This is the main code I'm struggling with: https://gdl.space/aqumuculuv.cpp
My errors are in the image.
The code that I'm getting my bools from is this: https://gdl.space/oyojomafuk.cs
what image? also a null reference error is always the same. Something is null, and you're trying to use it. You just need to figure out what exactly is null, theres 3 references in the first class that could be. Then you just need to figure out why its null, like maybe that FindGameObjectWithTag didnt find anything. Maybe you didnt drag in the references for the other scripts
also belongs in #💻┃code-beginner next time
Hello everyone!
I'm asking here cause I feel like I'm going to explode this is so frustrating.
I have a horizontal layout group with two text meshes and an image in the middle like in image 1.
I want to make it so that the rect adapts to the size of the text inside (as in image 2 to image 3).
I can't put content size fitters on the text since they're children of a layout group and it fs everything up.
Any Unity UI pros have a solution for this? I can't belive I'm having so much trouble with this
This is a coding channel #📲┃ui-ux
Oops. I don’t know what happened to my image. The error was stating something wrong with my trailsActive = settings.trailsEnabled; I don’t know how it would be null though. In the other code, there’s no way for the bool to be null. It’s also not the tag as I made sure to enable them
I’m hardly a pro at anything but I think TextMeshPro has a recommended size somewhere in the inspector that changes based on length of text. Maybe there’s a way to read that and transform it based on what it says there? Don’t take my word for it
You're guessing at what's null, add debugs and find out.
Hint theres only one thing that can be null on that line.
Show your code
I forgot all about those. I’ll continue working on it later when I can and try out those
No error it just does not work
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What debugging steps have you taken? What are you expecting it to do? What is it doing instead?
nothing does not give any debugs
I got that error
Then the code isn't running at all presumably
Or it's failing before getting to any logs
Make sure it's actually attached to an object in the scene
And add more logs at the beginning
using System.Collections.Generic;
using UnityEngine;
public class CameraManager : MonoBehaviour
{
public Transform target;
public float cameraSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = Vector3.Slerp(transform.position, new Vector3(target.position.x, target.position.y, transform.position.z), cameraSpeed);
}
}```
No need to crosspost, you're already getting help in #💻┃code-beginner
Didnt get any useful help
in editor i get the debugs but on phone when i port it to test i dont get any
target is destroyed but you still try to access it on CameraManager line 19, as the error says
Errors have stack traces, which describe where the execution was exactly when the exception occurred
The help you received looked spot on
did not work for me
I think praetor meant to reply to neo there
fair well it does not work and the logs work in the editor not on the phone
and your build platform is?
andriod
so you have the LogCat package installed?
no whats that?
that is the package you use for debugging problems in an android build at runtime
Well my phone wont link to my pc right
then I cannot help you further
i using dotween to roll obj, 180 degree, can i somehow controll the direction to roll? i mean clockwise or counterclockwise?
linked now
have you tried -180?
So install the LogCat package and build and run
I will try again since i did not open the LogCat window
the only errors i see are something with charging
nvm
you should at least see some debugs which I am presuming you have added to your code
some 2024-07-13 14:50:24.475 32149 32256 Error Unity AndroidJavaException: java.lang.ClassNotFoundException: com.google.android.gms.games.PlayGames
Yea i see them
this tells me there isa a problem with the PlayGames setup which I know nothing about. Perhaps ask in #📱┃mobile
i just needed to google more and find the right github comment its fixed now i just have a script error that i can fix
is it only me or is the AR Foundation Documentation really bad?
Im trying to migrate a project to Unity 6 but some functions arent there anymore and I cant find any mention of a deprecation for these, not even from the Version where they were avaiable and then the next version where they are not its not even mentioned that they are removed or that it is a breaking change... 🙄
Why don't Google Play services work for me? I use this code but absolutely nothing happens in the game
worldPosition is a Vector2. How is the GridLayout.WorldToCell method with a Vector3 as its parameter is used instead of my extension method with a Vector2 and can I correct it?
I understand that Vector2 can be implicitly converted to Vector3, but, I suppose, it should still use the one with Vector2 as the parameter
Error message? Looks like the error targets what you pass to TryAddTileInternal() (wrong return type?), not the extension method
That's because the UnityEngine's method returns Vector3Int, which cannot be implicitly converted to the method's parameter, Vector2Int
The error would disappear if I could've used my extension method
Force the usage by calling the static method directly and see if that solves it
Can you post the complete error from the console?
The issue is not in the error
I have mentioned the error, it just cannot convert Vector3Int to Vector2Int
Surely, the issue is resolved, when referencing it this way
TryAddTileInternal(TilemapExtension.WorldToCell(torsoTilemap, worldPosition));
I'm just wondering why is the "2nd of 2" method used here
Not certain if that's the issue. Posting the error would tell us what's really happening rather than trying to solve an issue that isn't a factor.
Overload resolution is pretty robust, I'm pretty sure it chooses the overload with the exact types first, before trying to make conversions in an attempt to use others
Post the full error and the full !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.
I have already told the whole error
CS1503
Argument 1: cannot convert from 'UnityEngine.Vector3Int' to 'UnityEngine.Vector2Int'
That's why it should chose Vector2 for Vector2, instead of Vector3?
No, a single one
Please post the full code
public bool TryAddTile(Vector2 worldPosition)
{
if (Length == 0)
return false;
return TryAddTileInternal(torsoTilemap.WorldToCell(worldPosition));
}
private bool TryAddTileInternal(Vector2Int position) =>
TryIncreaseLength(position - TailPos);
//
public static Vector2Int WorldToCell(this Tilemap tilemap, Vector2 worldPosition) =>
(Vector2Int)tilemap.WorldToCell((Vector3)worldPosition);
I'm assuming the actual error is with Try add tile internal wanting a vector 2 and not your extension method refusing to implicitly convert types.
It's not my extension method, because it's not even used here
Where you're trying to explicitly use your extension method that returns a vector 2 instead of resolving the error - xy problem.
My extension method is not used
Either way, the error is on that line but isn't likely related to the extension method
The error can be ignored, I'm asking whether it's possible to use my extension method without referencing the class directly
Well, the method was implemented to remove the explicit Vector3Int to Vector2Int convention, but it seems, because of my extension method not being visible, I will have to do it anyway
Checked out the spec, the overload resolution steps for extension methods come after the step with converting types. So it'll first convert your parameter to a Vector3Int before calling the instance method. Spec mentions return types are not taken in consideration when resolving overloads
I AM SO MAD RIGHT NOW I GET THIS EVERYTIME AND IT IS SETUP RIGHT I HAVE OCTUPLE CHECKED IT
Error PlayGamesServices[SignInAuthenticator] **** APP NOT CORRECTLY CONFIGURED TO USE GOOGLE PLAY GAME SERVICES
Error PlayGamesServices[SignInAuthenticator] **** DEVELOPER_ERROR
Error PlayGamesServices[SignInAuthenticator] **** This is usually caused by one of these reasons:
Error PlayGamesServices[SignInAuthenticator] **** (1) Your package name and certificate fingerprint do not match
Error PlayGamesServices[SignInAuthenticator] **** the client ID you registered in Developer Console.
Error PlayGamesServices[SignInAuthenticator] **** (2) Your App ID was incorrectly entered.
Error PlayGamesServices[SignInAuthenticator] **** (3) Your game settings have not been published and you are
Error PlayGamesServices[SignInAuthenticator] **** trying to log in with an account that is not listed as
Error PlayGamesServices[SignInAuthenticator] **** a test account.
Error PlayGamesServices[SignInAuthenticator] **** (4) A server auth code was requested, but an incorrect client
Error PlayGamesServices[SignInAuthenticator] **** id was provided. The client id for server auth codes should
Error PlayGamesServices[SignInAuthenticator] **** be the client id for the game server (not the android app).
Hi guys, I'm trying to make a grappling hook sort of mechanic. I followed along with a tutorial, but something is not functioning properly (my code is exactly the same, I've checked multiple times).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrapplingVine : MonoBehaviour
{
[SerializeField] private float grappleLength = 10f;
[SerializeField] private LayerMask grappleLayer;
[SerializeField] private LineRenderer rope;
//[SerializeField] private Transform playerTransform;
private Vector3 grapplePoint;
private DistanceJoint2D joint;
void Start()
{
joint = gameObject.GetComponent<DistanceJoint2D>();
joint.enabled = false;
rope.enabled = false;
//playerTransform = gameObject.transform;
}
void Update()
{
if (Input.GetButtonUp("Fire2"))
{
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
//origin: playerTransform.position,
direction: Vector2.zero,
distance: Mathf.Infinity,
layerMask: grappleLayer
);
if (hit.collider != null)
{
grapplePoint = hit.point;
grapplePoint.z = 0;
joint.connectedAnchor = grapplePoint;
joint.enabled = true;
joint.distance = grappleLength;
rope.SetPosition(0, grapplePoint);
rope.SetPosition(1, transform.position);
rope.enabled = true;
}
}
if (Input.GetButtonUp("Fire2"))
{
joint.enabled = false;
rope.enabled = false;
}
if (rope.enabled == true)
{
rope.SetPosition(1, transform.position);
}
}
}
Any clear issues or plausible causes?
to double check this is for 2d right?
correct
well you need a direction if you want to get anywhere
why is your direction Vector2.zero?
For some reason the guy in the tutorial said 'we don't really need a direction so let's use for example vector2.zero' 🤷♂️
I found it weird as well
which tutorial
Welcome to the How To Make Any Game Mechanic Series. In this series, I take you step by step, to create viewer suggested game mechanics. If you have an idea for a future video, leave it in the comments bellow!
Episode GitHub: https://rb.gy/zhym6
My 2.5D Course: https://www.gamedev.tv/courses/unity-2-5d-turn-based-combat?coupon=action&ref=ztfi...
so whats wrong with your thing in comparison to video
Mine doesn't do anything that happens in the video haha
idk what "but something is not functioning properly" means
ok so what happens instead?
it doesn't enable the distancejoint or the linerenderer
and when I do manually the linerender is in the correct place that i clicked, but the distancejoint pulls me far off the map
did you check the console window ?
maybe make a video of issue
The only thing that's different btw is that I'm using a cinemachine camera, but I was hoping that that wouldn't matter with the 'Camera.main.ScreenToWorldPoint(Input.mousePosition),' line since I figured cinemachine just overides the main cam
Aight
And yeah, clicking does disable the linerenderer, but it doesn't draw it for some reason
which object has the script
the player
Oh damn
I had the first code block set to buttonup instead of down, so now the linerenderer and distancejoint do get activated, but the joint is still pulling me away 😓
So the code is looking like this now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrapplingVine : MonoBehaviour
{
[SerializeField] private float grappleLength = 10f;
[SerializeField] private LayerMask grappleLayer;
[SerializeField] private LineRenderer rope;
//[SerializeField] private Transform playerTransform;
private Vector3 grapplePoint;
private DistanceJoint2D joint;
void Start()
{
joint = gameObject.GetComponent<DistanceJoint2D>();
joint.enabled = false;
rope.enabled = false;
//playerTransform = gameObject.transform;
}
void Update()
{
if (Input.GetButtonDown("Fire2"))
{
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
//origin: playerTransform.position,
direction: Vector2.zero,
distance: Mathf.Infinity,
layerMask: grappleLayer
);
if (hit.collider != null)
{
grapplePoint = hit.point;
grapplePoint.z = 0;
joint.connectedAnchor = grapplePoint;
joint.enabled = true;
joint.distance = grappleLength;
rope.SetPosition(0, grapplePoint);
rope.SetPosition(1, transform.position);
rope.enabled = true;
}
}
if (Input.GetButtonUp("Fire2"))
{
joint.enabled = false;
rope.enabled = false;
}
if (rope.enabled == true)
{
rope.SetPosition(1, transform.position);
}
}
}
Why
welp, i think i've done it now
I've broke unity in a way I've never seen before
with System.Reflection....
ah wait
no it's just because I had my scripting system infinitely calling itself.
that would do it
hahahaha yessssssss
Auto-Syncing values via reflection woooork
nБЛЯТЬ ПОМОГИТЕ\
it does not work and i get that error and i have it setup
Understand
and the fixes people have made online does not work
I'm also trying to find recommendations on the Internet for my problem, but I can't find anything. I only have the option to roll back to the old version of the plugin
also Google Play Service?
Yes
I just have nothing happening in the game and no results in the console
In the test scene, manual authentication goes on forever
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it works for me i just get a Google Play Error because i think the plugin is broken for me
Okay, thanks
since i had same error before i made this script with a lot of debugs
I'm going to try now
nice i hope it works for you
Thanks for helping even if it doesn't work
It works for me
Unfortunately, my console does not show any errors and nothing happens in the game
are you sure that you the script is on a gameobject
Yes
then idk
I don't know what to put in "token" and "error"
nothing they should fill out
So I did everything right
I heard something about logcat
Like it produces more detailed reports
I'll have to try it tomorrow
yea i use that when i test on my phone
Okok
yea i am sry
In here, the "Type" field is an enum. It renders properly in the very top at "Engine" but further down inside Menus>Submenus the "Type" just renders as an int. Why is that and how do i fix it?
Here's how a button looks.
An enum is just an int, in the yaml it's just the int that's stored. Though I dont know exactly why it breaks when nested so far.
https://forum.unity.com/threads/enum-becomes-int-in-inspector.527822/
Seems others had this issue as well
I'm aware that an enum is an int, but still thank you for the clearification!
Yea, it's a mystery why it breaks i guess... It's nothing i can't live with tho. Thanks For the heads up!

My guess is you're coming close to unity's serialization depth limit, not sure why it causes that though
What is the serialisation depth limit?
It's mentioned here but its basically their lightweight way of preventing infinite cycles
It says seven in this article but I believe the limit is 10 in newer versions
Ah, good to know.
I design my Debugging menu inside the inspector so i hope i won't run into this issue very fast :P
is there any specific order in which OverlapCircleAll puts the colliders inside of the array it returns?
is it like, completely random, or closest to furthest, or smth else entirely
there is no guarantee of order, you have to do your own sorting
so its arbitrary? good to know, thanks
I think that's only for 3d. 2D OverlapCircleAll docs say
The Colliders in the returned array are sorted in order of increasing Z coordinate.
right, should've checked the documentation first
didnt know it was different for 2D.
Nor I, until this moment 😉
huh thats interesting
why z specifically i wonder
But I guess it would still be arbitrary within the same z coord 🤷
tru
yeah i know, i guess thats a way to make it carry additional info in 2D
if they're all on Z of 0 how do you know which one is closest to origin
I'm having an issue when trying to display a multi type list in the inspector where I retrieve a serialized reference to the list. The issue is that when i was using serializefield, the data was displaying on my custom inspector fine but now that I'm using serializereference, the data for each propertydrawer doesn't show up when pushed to the property is passed to my inspector GUI. Is there something I can do? I'll post the code here in a bit but has anyone come across an issue like this?
I have been losing my mind over creating a screenshot system and I can not find anything helpful online.
This is supposed to enable a secondary camera, cam, that applies what it sees to a Texture. The main camera SHOULD continue rendering like normal while all of this goes on.
When the main camera is at a higher priority than the screenshot camera, the main camera's view is applied to the texture and the screenshot camera is ignored. If I have them at the same priority then the screenshot camera takes over and the screen obnoxiously flickers between the two cameras.
Is it possible to have the screenshot camera take a snapshot of its view without interrupting the main camera?
private IEnumerator TakeSnapshot() {
yield return new WaitForSeconds(0.0625f);
cam.enabled = true;
yield return new WaitForEndOfFrame();
var currentRT = RenderTexture.active;
RenderTexture.active = cam.targetTexture;
cam.Render();
var rect = cam.pixelRect;
int w = Mathf.RoundToInt(rect.width), h = Mathf.RoundToInt(rect.height);
int trueSize = Mathf.RoundToInt(h * 0.75f);
Texture2D snapshot = new Texture2D(trueSize, trueSize, TextureFormat.RGBA32, 0, false);
int startX = (w - trueSize) / 2;
int startY = (h - trueSize) / 2;
snapshot.ReadPixels(new Rect(startX, startY, trueSize, trueSize), 0, 0);
snapshot.Apply();
int halfSize = Mathf.RoundToInt(trueSize * 0.5f);
snapshot = GPUTextureScaler.Scaled(snapshot, halfSize, halfSize);
OnScreenshot?.Invoke(this, new ScreenshotEventArgs { screenshot = snapshot });
RenderTexture.active = currentRT;
cam.enabled = false;
}```
Thanks, using circlecast to detect angle is easier than the hack way I was doing lol. Can you explain the second part again about detecting corners?
Saving and loading player data in a multiplayer game, I want to save from the server and load from the client, any advice from experienced people ? I used to use sql in a www request, any better options ?
you can do it more simply like this
void SaveCameraView(Camera cam)
{
RenderTexture screenTexture = new RenderTexture(Screen.width, Screen.height, 16);
cam.targetTexture = screenTexture;
RenderTexture.active = screenTexture;
cam.Render();
Texture2D renderedTexture = new Texture2D(Screen.width, Screen.height);
renderedTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
RenderTexture.active = null;
byte[] byteArray = renderedTexture.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/cameracapture.png", byteArray);
}
Why would you want to load from the client?
What could be causing this? it shouldn't be my movement script, i've tried 2 of them and they both do this:
upload vids as mp4 so they are viewable on discord. Also look at the #854851968446365696 on how to ask a question, this is incredibly vague.
sorry, i dont really know what other info to provide, if tried messing with my rigidbody settings and that didn't change anything. I'll reupload it as an mp4
🤷♂️ consider that the literal only thing you've shown here is a video of an object moving around. You didnt describe the issue either. You just said "What could be causing this?" and that it shouldnt be the movement script. You didnt even show the movement script
I could take a wild guess and say its the movement script, because thats the only script im aware of here
I can provide my movement script if you'd like (the problem is the slight camera jitter)
we dont know anything about the setup right? the more you share the better. Script is good start
it looks like a mistmatch between how you turn the camera vs how you move
The terrain camera has it's rendering off, it's just something required by the asset I downloaded
I've tried a script i've made and someone elses and they've both done it so that's why I don't think its the script
idk ur mixing MovePosition with addforce which is already sus
also rotating in Update with a rigidbody
should show the setup for player, like the inspector n colliders. is camera child of player?
And yes, the camera is a child
Thats what it automatically set it as because my player is a cylinder with a box collider
Hey um I had an error trying to build a vr game can anyone help?
show the gizmos selected in the scene
whats your idea
is it just when you are moving or when standing still and rotating?
its only when moving/falling
did you try moving with AddForce / Velocity instead of MovePosition
I think collision/gravity might be fighting each other with the moveposition
Yes, that's what I tried initially
This is my intial script:
https://gdl.space/xigucovucu.cs
btw besides Impulse , any interactions with rigidbody should be done in FixedUpdate
that includes rotation
I know, I should probably move it into there, but i tried that a little bit and that was still causing it
idk do you really need it to be a rigidbody ?
why not just use a simple character controller
this is hella wrong btw mouseSensitivity * Time.deltaTime;
never apply time.deltaTime to MouseInputs
mouse is already framerate-independent
I don't think I need it to be a rigidbody, I could probably change it
pretty much plug n play with a few tweaks
what you have already should work, i would just try it with a cc instead. Replace the rb.AddForce with cc.Move
that crashed unity 😭
for future whenever you do something like this:cs terrainCam.transform.position = mainCam.transform.position; terrainCam.transform.rotation = mainCam.transform.rotation;
https://docs.unity3d.com/ScriptReference/Transform.SetPositionAndRotation.html
use this instead
uhhh what lol
the code is bad but i dont see why it would crash unity
many things wrong
did you see the first link i sent, cc should be moved in Update just fine so move all that back to update if you use cc
jump is wrong
all i did was change my original script
I'll try the other one
cc.Move(cc.transform.position + transform.TransformDirection(moveAmount) * Time.fixedDeltaTime);
can just be
cc.Move(transform.TransformDirection(moveAmount) * moveSpeed * Time.deltaTime)
this fixes the jittering but my movement is super weird:
also why is that rotation in fixedUpdate, you're not using rigidbody
well now ur using a third person movement style also no need to put in LateUpdate for camera, update should be fine since cc moves in Update and its parented
when i change in rider it then save the code in the cube doesn't change
once a script instance has been serialized the inspector values will always take precedence over the code values
how can i update it?
in real time
i tried refresh in unity didnt work
reimporting is very annoying
just to change stuff
remove the component and then add it back
thats the only fix?
yes
thanks !
Nah you can "reset" the component from context menu
unfortunately that option is broken in several versions of Unity
yeh
can someone help me remove this thing from rider its so annoying
the yellow lines under
What does it say
Ah that's actually super nice
It works well for me 🤔
Multiply your floats in paranthesis before multiplying them with the vector
Well it wants you to multiply speed and deltaTime first.. then vector
But you can turn it off
its good for optimizing it seems
may i know how?
does rider not have a quick action which will refactor this for you?
yes you should be able to alt-enter and fix it
Generally like this
Options are there if you press lightbulb
There is no reason to turn this one off, you should just fix your code. However you can turn the severity down if you want
in a learning stage like i am rn
its kinda hard
just alt enter and fix it?
How can I make sure my UVs stay the same size so that the textures don't stretch?
https://gdl.space/irujacutez.cs
You did this?
You can try basing the shader on the world position rather than UV.
https://www.youtube.com/watch?v=vIh_6xtBwsI
i was doing this thing and now unity is creating a work space for 8 min
When checking for the current KeyCode inside of the Editor.OnSceneGUI method in a custom Editor, pressing Control only renders after making a change, e.g. moving the scene around.
Is there any way to force it to render when I need to?
Debug.Log($"{Event.current.keyCode}; this: {target.name};");
SceneView.RepaintAll() does not seem to work
Alright, my bad. I was checking for Control, Event.current.modifiers should be used
Although, I'm not sure why keyCode displays as Control after changes made, if it should refer to modifiers
Hey,
How to get the image that the current camera rendered and how access a given pixel in it?
You could store that image in a texture I guess
What does "the image that the current camera rendered" mean?
How to store the current render texture in to an Image object?
I also don't need the whole image a 256x256 pixel sample is good enough for my application
Camera.targetTexture or where ever the current image is stored
I dont need the depth buffer I need the color buffer
I can't say for sure but I think there is a method called EncodeToPng or something. I am on my phone but you can look it up
Hmm, I'm not looking to take a screenshot I'm looking to detect a moving object via image contrast.
Ohh
My bad
So basically you want a color buffer of whatever the camera is rendering.
Exactly that
RenderTexture does not have a method to extract pixels. You can convert it to Texture2D using this method, then use Texture2D.GetPixel
Texture2D.ReadPixels seems like its what im looking for.
But is there a way to copy a small sample only
a 256x256 sample of the screen grab
definitely don't need a Full HD or 4K image for this
you have a byte array so an Array.BlockCopy can do that
this would be better
https://docs.unity3d.com/ScriptReference/Texture2D.GetRawTextureData.html
then you can sample a block of the array
Hmm, I still need to call ReadPixels to get the data to copy from
no, GetRaw gives you a pointer into the byte array without copying, so use the Array methods to extract the data
or just itterate over the RawData array
In the documentation sample they are taking the pixels from a material on a gameobject
I need the pixels from the screen.
var texture = new Texture2D(128, 128, TextureFormat.RGBA32, false);
GetComponent<Renderer>().material.mainTexture = texture;
// RGBA32 texture format data layout exactly matches Color32 struct
var data = texture.GetRawTextureData<Color32>();
which is why I linked this #archived-code-general message
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Texture2D frame = new Texture2D(256, 256, TextureFormat.RGBA32, false);
}
How would I go about copying the render texture in to the Texture2D?
src contains no method called GetRawTextureData
Did you even bother looking at the RenderTexture documentation
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
RenderTexture prev = RenderTexture.active;
RenderTexture.active = src;
Texture2D tex = new Texture2D(256, 256, TextureFormat.RGBA32, false);
byte[] data = tex.GetRawTextureData();
RenderTexture.active = prev;
}
In a custom Editor, is there any way to "focus" on it, so that most Unity shortcuts are ignored? For example, E shouldn't focus on Rotate Tool, and Shift + D shouldn't close the Inspector.
Now I assume that when I call tex.GetRawTextureData
it gets the raw pixels values from the src RenderTexture
How do you figure that? There is absolutely no relationship between tex and src
They are setting RenderTexture.active here
https://stackoverflow.com/questions/44264468/convert-rendertexture-to-texture2d
If I do
tex.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
Its gonna copy the whole color buffer and I'm going to copy way too much data off the GPU
And all that is gonna get garbage collected after. So its gonna be mega expensive
Dont exactly know what you mean GetRawTextureData returning a pointer to an byte array
That method returns a NativeArray<Color32> in this use case
I am having trouble doing this recoil thing:
private void Update()
{
//Other code...
//Need to somehow lerp the code below, here, since Lerp needs to be called constantly
}
public void DoRecoil()
{
//Other code...
//xRot & yRot are the cameras mouse inputs [---> (Input.GetAxis("Mouse X/Y") <---]
cam.xRot -= Random.Range(minXRecoil, maxXRecoil);
cam.yRot -= Random.Range(min_YRecoil, max_YRecoil);
}
I need to lerp the camera recoil, because it looks too rough and snappy without it obviously
I am not changing the camera rotation directly, because either the player cant move the camera, or theres strange tilts, so im doing recoil by manipulating the camera's mouse inputs, this seems to be a good approach
But I cant just Lerp(camera mouse input, recoiled mouse input value, speed) because that will force the camera to always look at the recoiled position, AKA cant move the camera freely
I dont know what to do at this point
Heres the whole method with comments explaining what I assume its doing
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
// backup previous render texture
RenderTexture prev = RenderTexture.active;
// set "src" RenderTexture as current RenderTexture
RenderTexture.active = src;
// Create sample texture 256x256
Texture2D tex = new Texture2D(256, 256, TextureFormat.RGBA32, false);
// Texture2d.ReadPixels reads from RenderTexture.active and copies from GPU
tex.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0, false);
// restore previous RenderTexture
RenderTexture.active = prev;
// Get raw pixels values from CPU
NativeArray<Color32> data = tex.GetRawTextureData<Color32>();
// dstOffset??? count??? how to use these?
Buffer.BlockCopy(data, 0 << 2, data, 3 << 2, 4 << 2);
// data is now ready
// ... do stuff
}
BlockCopy offsets are in bytes. You don't need to do any bit shifting there.
Do you know what the size of Color32 is?
In the doc example Buffer.BlockCopy used an array of 32 bit integers
int INT_SIZE = 4;
Buffer.BlockCopy(buf, 0 * INT_SIZE, buf, 3 * INT_SIZE, 4 * INT_SIZE);
So a presume I have to multiply by size of Color32
32 bits, which is 4 bytes.
https://docs.unity3d.com/ScriptReference/Color32.html
I'm not sure what you're trying to do. That calculation doesn't make any sense.
yeah I just put whatever was on the doc there
That would copy 16 bytes starting from the 12th byte, so it would skip the first 3 pixels and copy the next 4 pixels, if I get it right.
What docs?
I don't see them doing anything with colors though.
And the intention of your code is still not clear
I'm trying to sample the main camera render texture so that it can be used in object movement detection via image contrast.
Smith further up the message chain said to use the Buffer.BlockCopy method to copy data from the Texture2D.GetRawTextureData byte array
What are you gonna do with that data. Can't you use the tex after ReadPixels as is?
Thats why I am a bit confused.
I asked if I can sample a smaller part of the image so that I wouldn't need to copy whole image.
For the image contrast I just need a low resolution version of it.
Just a 256x256 sample of the whole source RenderTexture
If you want a smaller version of the render texture, you'll need to downsample it.
If you want to sample a smaller region from the whole texture, then ReadPixels would work
Yes, how to do that though?
because this copies whole screen
tex.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0, false);
Hm... Does it?
If so, then just use different values instead of src.width and height
use the width and height that you want to sample.
tex.ReadPixels(new Rect(704, 284, 256, 256));
would copy a 256x256 sample from the center of a 1920x1080 screen
Yeah, something like that
I could make a ScreenManager of some kind and copy the whole screen every frame and store in a Texture2D and then sample it later
But I don't know how ReadPixels works. If I am sampling a 1920x1080 area in to a 256x256 texture 2D is it automatically gonna downsample?
No, it shouldn't downsample from what I understand.
But you said here that it does? Or is that not what you meant??
because this copies whole screen
I meant I only need to downsample the whole screen in to a 256x256 texture without copying the entire screen
The whole screen resized to 256? or a 256 part of the screen?
whole screen resized to 256
Well, you can't do it with just ReadPixels
As I said multiple times already
I dont want to transfer the whole screen from the GPU that will take ages is there a way to sample into a 256x256 directly?
Problem I have is not wheter if its possible to downsize it, no.
Its getting only the amount of data that is necessary
- I think you exaggerate about "ages".
- If you really want to, you can down sample the texture to a 256 texture using a copy shader, and then read the downsampled texture.
You can't get only the amount of data that you want, that would mean handpicking individual pixels from the buffer, which would be tens or even hundreds of times slower than just copying the whole thing.
I'm pretty sure the "slow" here is not even the amount of data, but just the fact of copying. It shouldn't matter much for a modern hardware to copy 1mb vs 100mb of data from the GPU as long as it's done in one operation.
Hello can anyone help me with unity editor download
I am getting the problem of install failed validation failed can help me
The data is going to get garbage collected at the end how much of a slowdown will that be?
I will be sampling the screen grab after so I will have 31 times more data than I need, even worse on UHD screens
Depends on how much data. It also doesn't have to be collected by GC. That's up to you.
So if I store a reference in the class as a field the massive buffer wont get garbage collected?
will you please just spend 10 minutes to think about what you are trying to do
downsample a 1920 x 1080 into a 256 x 256 without reading all of the data, impossible
you are not even maintaining the same aspect ratio so that makes it doubly intensive
you are just totally not thinking about this
Yes. As long as the array is referenced, it wouldn't be collected/
Bro what is this attitude? Can't I ask questions on a discord server dedicated to questions? Even if some of those questions might sound "stupid" to you. This is quite loathing behaviour.
Ok, thanks.
What? All I asked you to do was think, is that really too much to ask?
hey was looking for some advice. im trying to build a pc/vr game and i wanted to have a check box to enable and disable vr. everything ive found looking online has been very general and niche.
@daring cove bro I don't think this server is to spoonfeed you answers rather help you solve the problem. Also my advice is to listen to @knotty sun He has helped me many times in the past and trust me it helps in the long run.
I don't think it's possible to "enable/disable vr". You'd probably need 2 separate builds.
supposedly its possible.
i found this script while looking through some forms
`XRPluginManagementSettings.cs
using System;
using UnityEditor;
using UnityEditor.XR.Management;
using UnityEditor.XR.Management.Metadata;
using UnityEngine;
namespace FrameSynthesis.XR
{
// ref. https://docs.unity3d.com/Packages/com.unity.xr.management@4.1/manual/EndUser.html
public static class XRPluginManagementSettings
{
public enum Plugin
{
OpenXR,
Oculus,
OpenVR
}
public static void EnablePlugin(BuildTargetGroup buildTargetGroup, Plugin plugin)
{
var buildTargetSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup);
var pluginsSettings = buildTargetSettings.AssignedSettings;
var success = XRPackageMetadataStore.AssignLoader(pluginsSettings, GetLoaderName(plugin), buildTargetGroup);
if (success)
{
Debug.Log($"XR Plug-in Management: Enabled {plugin} plugin on {buildTargetGroup}");
}
}
public static void DisablePlugin(BuildTargetGroup buildTargetGroup, Plugin plugin)
{
var buildTargetSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup);
var pluginsSettings = buildTargetSettings.AssignedSettings;
var success = XRPackageMetadataStore.RemoveLoader(pluginsSettings, GetLoaderName(plugin), buildTargetGroup);
if (success)
{
Debug.Log($"XR Plug-in Management: Disabled {plugin} plugin on {buildTargetGroup}");
}
}
static string GetLoaderName(Plugin plugin) => plugin switch
{
Plugin.OpenXR => "UnityEngine.XR.OpenXR.OpenXRLoader",
Plugin.Oculus => "Unity.XR.Oculus.OculusLoader",
Plugin.OpenVR => "Unity.XR.OpenVR.OpenVRLoader",
_ => throw new NotImplementedException()
};
}
}
`
but im not sure how to implement it. like do i have both the main cam and the xr rig in the same place? do i put it on a button or a toggle? stuff like that lol. im willing to learn but this just feels very hidden away lol
As you were told, you will need multiple builds, the code you posted is part of a build pipeline
i understand 😊
also, for future reference !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.
wait so if i wanted to make it to where pc players and vr players can play together, is that not possible?
got it thank you!
you would need a server build which both access to do that
Multiplayer is a totally different topic. It's possible, but is not very simple.
i see...
this is VERY non trivial
is it cool if i keep coming back for advice? im still pretty new to unity. but i have a lot of experince in other lanuages. this is just my first attempt at somthing a little more pro LOL
absolutely, that's why we are here
and probably u need to have a very good running server too
im not even in alpha stage for brutus yet lol that feels like a problem for later me XD
the server will not be the bottle neck, the bandwidth, however, will be
yes right steve.
so if i could get some idea of where i need to be looking for some idea on how to make the builds and where to do so?
wait so that means i have to make two .exe files of my game? one with vr and one without?
Yes.
No. You don't have to. I think it would be simpler to have it as one project. Unless you need to build very often.
so i wouldent have to remove all of my xr stuff. i could just disable it?
Yes. In the worst case, you might just need to have separate scenes or prefab. It depends on how you're structuring your scenes/prefabs and loading the game.
that is the point of build pipelines, you just include the stuff you really need for that particular build
oh gotcha. again im sorry im still really new.
Maybe start with a non vr game then
lol. im probly gonna build it as a 3d platformer and move into vr
ive had this in the idea stage for way too long and ive finnaly had the motivation to just do it.
Ideas don't worth much if you can't bring them to a fruition. And jumping into a complex project without having any experience is a good way to ruin your idea.
very fair. im just trying to figure out how to break things up into easier to chew peices. right now the vr portion is what is throwing a wrench into things. so it will be somthing i approach at a later date.
Hi. in 3D, what's the best way to make a wall check? I will need wall normal (slope). Is there a better way then casting rays?
Collision messages or casts. That's about it.
i tried getting normals from onCollisionEnter, but you cant get them back from onCollisionExit so you cant tell when you exit the wall sometimes
Why do you need the normal on exit?
I don't think you should be using the normal to identify the wall anyway
to compare the slope angle to determine whether it's wall or ground
well i could do a separate layer for walls
but then there could be problems if we're colliding with a non plane object
cause the normal can change
you can raycast from the player to the collider to get a normal
yeah i guess i will have to do that
It is not ordered
I just want to confirm one thing:
are
transform.Translate(Vector3.up * speed * Time.deltaTime, Space.World)
and
transform.position += Vector3.up * speed * Time.deltaTime
the same?
I'm aware of Space.Self and Space.World, i just want to know if there's any other difference between directly setting an objects position vs using Translate in world space
If we ignore forward instead of up used in the 2nd variant, yes, they are the same
ah yes, sorry
You can have a look the Translate method. It uses position's set, when the world space is chosen
if (relativeTo == Space.World)
{
position += translation;
}
else
{
position += TransformDirection(translation);
}
thanks!
Is there any way to properly figure out what mouse button is pressed in the Editor?
Event.buttondescribes which mouse button was pressed
0 means left mouse button, 1 means right mouse button, 2 means middle mouse button
I thought it would be better to make an enum out of it, but it's an integer.
So, perhaps, no mouse button pressed may be -1? No, it's 0 too.
According to Unity, checking for no button pressed should be done with
e.button == 0 && e.isMouse
But isMouse returns true not just when being held, but also when moved, which means e.isMouse being false doesn't necessarily mean no button is being held.
I wish Unity's Input system would be usable in the Editor instead of Events
What do you mean?
I mean that I have a desire to use Unity's Input system instead of Events in the Editor
Can't you just check if(Event.current.type == EventType.MouseDown)
It returns false if a key is being held, so that the type is EventType.KeyCode. The same goes for any other EventType
I suppose, I may consider changing a newly created variable by checking for MouseDown and MouseUp, but I wonder how accurate this is going to be, because these events may get lost when exiting the custom Editor
Alright, this seems fine
public enum MouseButton
{
None,
Left,
Right,
Middle
}
if (evt.type == EventType.MouseDown)
_currButton = (MouseButton)(evt.button + 1);
else if (evt.type == EventType.MouseUp)
_currButton = MouseButton.None;
is this smart or dumb
Neither, if it works, don't worry about if its the best way to do it.
👍
this works until you have other things that can have an effect on the movespeed like enemies slowing you, then you want to establish base vars for "movementSpeed", "runSpeed", etc, and recalculate the "currentSpeed" whenever something changes your movespeed, but for your case right now its perfectly fine
thanks!
I wonder if there's a better way to check if a list of objects have reference to a specific game object among them than doing a foreach with a bool?
/// <summary>
/// Force-add an object as a potential target
/// </summary>
/// <param name="quietly">new target won't have maxed out freshness</param>
public void InjectTarget(DynamicObject actor, bool quietly = false)
{
if (actor == null) return;
bool contains = false;
foreach (AITargetObjectReference knownActor in potentialTargets)
{
if (knownActor.reference == actor)
{
contains = true;
break;
}
}
if (!contains)
{
AITargetObjectReference item = new(actor, quietly?5:11);
potentialTargets.Add(item);
}
}
list.Contains
or rather list.Any would be more appropriate since you're checking a field on objects in your list
I am currently trying to make sort of worm procedural animation. But I have an issue where instead of the objects following each other, they seem to be swapping sides of the main part. https://hastebin.com/share/wodumihodu.csharp. Here is a video of the issue: https://streamable.com/pa18e6
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The problem is that the list if of AITargetObjectReference, a class containing relevant information about potential targets AI can sense (see or hear), while I want to check if any of those targets points to a specific DynamicObject component of a GameObject.
read literally the next message i sent
of course any of those methods would just loop over the list anyway so it's really up to you whether you actually change it
from pyngrok import ngrok
port = 5004
ngrok.set_auth_token("my ngrok auth token")
public_url = ngrok.connect(port)
print(f"Public URL: {public_url}")
!mlagents-learn --force``` anyone know why this doesn't work or should I use something else, I'm trying to use mlagents in google colab. I have all dependencies installed
yeah but does anyone know
I'm quite unsure why the objects are following eachother like that, instead of following like a chain.
Not in this channel
Ah, sorry. How do I use it, exactly? Something like this? I've found this whole "from where" structure in Ms docs about .Any, but I'm unsure how .Any is useful in this situation, seems like it should return, well, "any" non-empty reference?
contains = (from knownActor in potentialTargets where knownActor.reference == actor select knownActor.reference) != null;
did you look at the docs for the method?
yes
Well it does says that it only checks if the element exists, not whether it matches anything specific.
true if the source sequence contains any elements; otherwise, false.
if only there were more than one overload. since the scroll wheel doesn't exist we'll never know if that is the case
how can I have multiple colliders in a gameobject or in seperate children gameobjects and detect seperate collisions to do seperate tasks like a left side collider, rightside collider, etc
this gets messy
just use physics queries
maybe use colliders just to set their sizes, depending what you're doing with them
You could potentially put them on different gameobjects, and use same script with an enum to tell which side you are calling from, but thats way more work than just using physics queries
should i be using collider cast?
nahh
use stuff in the Physics class
like Physics.SphereCast etc
you can also do raycasts but they're thin so it depends what ur doing
ohh like the SphereOverlap?
yea those are physics queries
overlap though doesn't give certain info casts do , like Raycast hit
just collider, if thats ok with you then yeah overlap works
yea overlap doesnt really give info i was gonna ask about that
so like something like sphere cast
would i be able to see it in unity real time
kinda like how i can see a box collider's collision area and edit it in the editor not just in code
you can see it in realtime yes
You would have to expose the Vector3/float size in inspector to change it realtime during playmode, see which sizes you need
Cool new debugging features inside Unity 2022+
OnCollisionEnter gives you a Collision, which has Contacts, which have the colliders involved in the collision - thisCollider and otherCollider
thx alot man. just another question, how do i give my overlapcolliders a name or a tag
It's not something you give a name to
if i choose othercollider, would i be able to specify which one?
OverlapCollider is not an object, it's a function you call
so i add my colliders in that last array argument right?
Not sure what you are asking. You could use it to detect which collider was hit
Which I thought was your initial question
No, that is the array that it writes the results to, read the documentation
my bad yea this is what im looking for
bet bet, thx alot 👍
Since you are working in 2D it is slightly different
OnCollisionEnter2D>Collision2D>collider/otherCollider
I think otherCollider is the "self" collider 🤔 I just remember the naming being a bit misleading in 2D
im not to good at finding what im looking for in the documentation but i found this while looking for it and it doesnt feel like using the other.gameobject identitfy which collider has been hit
That is OnTriggerEnter2D
Hey fellas, whats more optimal for a tank like set up (multiple weapons at different points on the player)?
A single script that flags when to fire attatched to the main object, finding each weapon within holders? OR
Many scripts looking for flags under the input script that handle everything?
doesnt apply for triggers?
With triggers there is really no way to identify which self collider was hit unless they are on separate objects with separate components that has OnTriggerEnter
And if the colliders share the same rigidbody then I think the message ks sent to the rigidbody object, not the collider
What is the functionality you are trying to make here?
Hold on, I have an idea between both,
I can make one script in general and just use a switch to differentiate between flags
Hello, i am doing an constant checking on my player's state and change it's animation based on the current state it's in. However i feel very insecure and feel (i am sure) that this code is bad, could someone tell me how to improve?
can some1 check for a scam link?
i am trying to detect whether my gameobject is touching the ground from left, right, up or down
I can try to send in another link, wait
charactercontroller.isgrounded :DDDD
send a picture or copy and paste it bratan
It's a trusted site
gdl.space is safe.
Physics query is probably easier then, like OverlapBox
Posting code via screenshot is explicitly discouraged
oh fr?
i tried using physics.overlapcollider if thats what u mean
The code is kinda of big for it
I'm looking for another site
No you're good, the one you have is fine
Well I guess that works too if you want to use pre defined colliders
https://hastebin.com/share/ogacixulix.java Just for making sure, and i don't know why it's in Java ^^,
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how can i get them to be pre defined
Hello, can you send me a code to open and close the door in my Unity game by pressing the E key?
my fualt my bad
By making them
like having them in sperate gameobjects and naming them?
And then calling OverlapCollider with each collider as a parameter (separately)
Sure
ok ty
dawg dont let him figure it out himself
that font lmao
Some of it looks a bit convoluted (like the bulky conditions in DetermineAnimationState()), but that's pretty much as good as you can get without changing the whole system
I would change the whole system to use an Animator controller with parameters, so you don't manage the animations from the code directly
Could I please get some help with this, I'm still stuck.
They will most likely just copy-paste the thing without reading it, and return complaining that "it doesn't work" because their object setup is different.
That is usually why we don't do handouts like these, but help with existing code instead
that and just giving someone the answers likely wont help them in the long run
hands on learnign is the best
no need to spam a big ass message when you can use pastelink websites..
And yeah chatgpt code is even less ideal lol
by every study
And thank you for it, however i cannot use Animator in this project for a reason, so is this code not TERRIBLE?
just giving someone the whole code goes against the philosophy of the server..
For a reason... it's decompiled/ripped, isn't it
how about you just dont post it?
the dude joined to ask for code, not programming a thing as if were just an AI tool for him to use
I dont think anyone like that deserves any help
Didn't know that, i'm sorry
Won't happen again 
its good to be kind dude. but its even better to know when that kindness is being taken advantage of
too much love'll killa ya
this isnt optimal is it?
any better alternatives?
its a general use case for multi flag case for a tank
use an array
Hello I am making aparty game similar to mario party, in the game each round being a random map, a random gamemode and a random modifier
Does anyone know a tutorial or any documentation to make this system work?
right thank you
Noted, thanks for the warning
you mean a very specific thing ? doubt it lol
you have to learn how to break down these systems and build them yourself
i don't see nothing wrong with it, would just follow nava's tip and would use an array instead
Well I am trying but idk where to start or how to start😂
you would have to define all those things and what they mean. What is a gamemode, etc..the level part is the easiest since you can just randomize an Int for a SceneManager.LoadScene
fr. Now if I want to make a suggestion that you should change something in that code, I either have to very verbosely describe the change and where to apply it, or create an example by manually transcribing all of the relevant code in the image by hand. If I want to test some portion of your code myself, then I must type it all out.
Demonstrating like a contextual error message with an image makes sense. But sharing code that way is just an unnecessary obstacle for anyone who might want to address the issue... In this specific case, it also means interested parties must grapple with a wacky non-monospace font 😅
dawg I was joking about my font choice but good point
Honestly it did give me a chuckle
if you aint progamming in the terraria font you aint progamming good
If this is a multiplayer thing, depending on how you store your data for maps, game modes, modifiers etc, you could give them an ID such as through a database or a persistent ScriptableObject list that does not change between clients, the host could randomize the index selection and send those indexies over the network - thats one solution that comes to mind, but it would also assume your data can be stored in a list/database structure
I am facing another problem were in each gamemode the character controller is different is some minigames the player can only jump other mini games depends on who spam a button
How can I change the character controller depending on the mode
I've got a strange bug that I can't seem to figure out.
I'm making my own player movement script, and everything works fine, including that if I hold space, my character automatically jumps when they hit the floor again. (As intended).
What's not intended is that occasionally my player jumps 2-3x as high as other times while I hold spacebar. It's incredibly inconsistent. Any ideas?
Here's my script so far: https://pastebin.com/geNJDwMC
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.
If this isnt some competitive game, you could just have 1 controller and then enable/disable input action maps based on which mode it is.
likely multiple calls to the jump function frame after frame
yeah
So I should start with making it multiplayer and learn networking and databases?
no
if you are just starting out start small
3 arrays
array 1 is for gamemode
array 2 is for map
array 3 is for modifier
have a random for each
I assumed your game already is multiplayer, maybe I misunderstood your question, is your goal to send information to other players or is this a single player experience? Is this all happening on 1 machine or across many?
Did you plan for it to be multiplayer? If so then youd need to make it multiplayer.
It's a lot harder to go back and make a single player game into multiplayer because lots of systems will have to change. But also if you arent really good at debugging, you likely aren't gonna get far in multiplayer
couch coop/vs will be ok. Networking you will struggle if you can't even start this system tbh
Ye this is the best idea rn
Thx alot
but yeah def look into the new input system cause you can easily swap out controls scheme
yeah its a little more complicated but its worth it
Debatable, depending on what the end goal is. It sounds like you arent even sure yourself.
You really wont have a good time trying to go from couch coop to online multiplayer.
You should define what you want first. Couch coop still isnt as simple as just singleplayer
Sebastian greaves has a series remaking dark souls where its used extensively, I suggest you give it a try https://www.youtube.com/@SebastianGraves
I have built a single player 2D puzzle game and a simple 3d shooter game I am looking for something a bit more advanced than before
That's fine and all, I'm just saying you should define what you really want in it. Like is the end goal to be making multiplayer games?
If so, and you want this game to be multiplayer then you'll have to start with that immediately. Multiplayer is not something you consider after
Do know any simple tutorial for making a muliplayer game I can start with?
can I see this simple 3d shooter game?
simple and multiplayer don't go together lol
When it comes to multiplayer, there is no simple. Codemonkey has a decent tutorial on getting the absolute basics setup for NGO which is unity's multiplayer solution
And similarly there arent many tutorials because most of the youtubers cant do it themselves
So I'm trying to path trace triangles, I'm currently having this weird issue where the side that should be casting shadows is not, and instead the reverse is true, how could this happen? I've tried reversing some normals, didn't work, just made the face unlit if it was lit from the correct side and had no influence on the shadows. If you need any specific code please tell me. I'm just first seeing if this is a common known issue haha
Ived learned this the hard way lol
I have watched a couple of tutorials of smithing called photon but I have yet to try it out
Is it any good?
same lol
havent tried it myself, i only used ngo. Im sure the concepts are similar but ngo is newer (i think). At least when i was trying it a few months ago it was being updated pretty frequently
Unexpected GridLayout Behavior
I have used Photon and they are actually a suit of services, such as Photon Fusion, Photon Quantum, Photon Unity Networking (or PUN, which I assume is the one you are referring to) - I would say PUN is the "simplest" to work with when it comes to multiplayer, but its also technically "outdated" (still usable and has support just doesnt get updates like NGO, Fusion and other solutions), so its often suggested to use Fusion as the alternative to PUN specifically - also keep in mind with any multiplayer solution, you may need to buy a subscription to what is referred to as "CCU"s, being the max number of players that can connect and play your multiplayer game, for Photon they offer 20 CCU for free to test and develop with, then when you are ready to release you can upgrade to 100 CCU for a monthly fee, or more CCU for a monthly fee if needed, they also support something called a "burst" where you have a influx of more players than your plan supports temporarily (you can imagine if you released a big update for your game when the sever only supports 100 players, and the update brings in 130 players, you dont want to kick those 30 players out so you kind of allow them at a cost per-player that goes over 100, in this example youd be paying a few cents each for those 30 players, ontop of your monthly cost for the 100 subscription), not sure if "Burst" is specific to Photon though, havnt used NGO myself
photon is horrible. they are free up to 20 players but after 20 players they charge an unbelievable amount of money. you are better off coding ur own system with websocket-sharp as you then have full control over hackers and can firewall them unlike photon which has no way of banning them from the network server sided
can somone explain why unity exports like this? meta developer hub is not uploading it and keeps throwing api errors.
whats "like this"
You can cover Photon bills with web ads. You'll have a hard time matching the quality of Photon Fusion/Quantum, especially if your starting point is WebSockets.
it exports D3D12
ive never seen that
where is monobleedingedge
D3D12 is prob for direct X 12
on meta things arent so easy sadly
What's inside the folder?
meta wont except it it should look somthing like this. idk if its a unity version or somthing but im confused why my app builds weird
did you export using IL2CPP?
D3D12Core.dll
check the scripting backend
yes
then yea u arent gonna have a MonoBleedingEdge if you dont use Mono
Sounds like d3d12 library.
Are you even building for the correct platform?
kk thats why then
ill try
How would I rotate a ui element like an image, with a text in it, but the text always stays at 0 degrees instead of rotating with the image (thats what I want) how could I do that?
make a common parent but only rotate image
i have a canvas based menu in my game. the items in the menu are represented as images that I can move around with mouse click. When I import the menu to start working in the game, the image no longer moves around with the mouse. No reference or errors of any sort. Wanted to see if anybody knows whats going on in case its a common issue. Already checked sorting layers and canvas render modes
yeah that's gonna be taxing its on an item that I drag with my cursor
wdym "taxing"
gonna just make it more hectic when the text is detached from the inventory item
I never said detach it from inventory item
do you know what having a common parent means?
Returning to this.
If anybody wants to migrate their OnMouse... events with 2D colliders to the new Input System, this should be "enough":
https://pastebin.com/kxbCCn7q
rename void OnMouse...() to public void OnRaycastMouse...() and inherit from the interface, then call UpdateMouseInput(); once per frame in some singleton.
It's horrible but it does the job.
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.
felt rude to me to essentially solve the problem but not give away the solution
but that's not even necessary when you can just use the already existing interfaces from the EventSystem. all that requires is the EventSystem in the scene and a PhysicsRaycaster2D on the camera
nope. if you read the conversation I was having back then - that stuff didn't work for me
the game has overlapping canvases which were "eating" the raycasts so I had to do it myself
the Unity's eventsystem + physicsraycaster2d might work if you don't do funky stuff with multiple canvases + depth in a single scene, but if you want the real "og" legacy raycast behavior - you must resort to Physics2D.GetRayIntersection for some unknown reason
Can someone please help me out? I've been stuck on this for four hours and nobody has responded to my message.
that sounds like something you should report as a bug tbh
perhaps, but in that conversation we ultimately decided that the OnMouse messages do some cursed eldritch legacy stuff that nobody knows how it works, and the new eventsystem + physicsraycaster setup just didn't work with the way this game handles canvases and cameras. so my goal was to replicate this legacy behavior somehow
and that worked, lol
Surely you want the else block to offset from the prev child not from itself? the first child
Yes
- parent.GetChild(i).transform.position = transform.position + (direction * -radius);
+ parent.GetChild(i).transform.position = parent.GetChild(i - 1).transform.position + (direction * -radius);
Oh lord, of course it was a simple solution. Thank you for the help!
it would help if you cached the transforms within the loop if you access them multiple times. It's much easier when you name things Transform thisChild = parent.GetChild(i); and Transform previousChild = parent.GetChild(i - 1); for example. Makes it easier to spot things out of place
Trying to build something similar to CS2s reactive smoke, and I'm starting with just getting voxel smoke working, but I'm finding that using 3D textures isn't very performant. Are there any other methods I should look into?
I feel I should also say that I do not know how to write shaders myself at all, and if this kinda thing is going to be impossible to do without shaders doing the heavy lifting, at least for the generation of the smoke (not the rendering, I'm happy to compromise on the actual rendering), then pls let me know that
how do i improve my code without tutorials, i havent really gotten on unity much ive made three simple scripts in total but i want to change that
thank you!
Is there any way to use #pragma surface surf StandardDefaultGI and #pragma surface surf Lambert vertex:vert together?
The following snip of script works with the 4 separate buttons.. but I want to use one button a + to use instead of four buttons just be able to press on the particular area of the + do do the same up down left right functions. i want the blank one to be normal state and the rest are up down.. etc... Any suggestions how to do this?
`// Button states
private bool leftButtonPressed;
private bool rightButtonPressed;
private bool jumpButtonPressed;
private bool downButtonPressed;
public Button LeftButton;
public Button RightButton;
public Button JumpButton;
public Button DownButton;
private void Awake()
{
camera = Camera.main;
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<Collider2D>();
// Set up button listeners with EventTriggers
AddEventTrigger(LeftButton, () => leftButtonPressed = true, EventTriggerType.PointerDown);
AddEventTrigger(LeftButton, () => leftButtonPressed = false, EventTriggerType.PointerUp);
AddEventTrigger(RightButton, () => rightButtonPressed = true, EventTriggerType.PointerDown);
AddEventTrigger(RightButton, () => rightButtonPressed = false, EventTriggerType.PointerUp);
AddEventTrigger(JumpButton, () => jumpButtonPressed = true, EventTriggerType.PointerDown);
AddEventTrigger(JumpButton, () => jumpButtonPressed = false, EventTriggerType.PointerUp);
AddEventTrigger(DownButton, () => downButtonPressed = true, EventTriggerType.PointerDown);
AddEventTrigger(DownButton, () => downButtonPressed = false, EventTriggerType.PointerUp);
}`
didnt realize the images would show up so large
Learning some dots and going over some open source code for reference.
I see method ending with the following
if(aNativeList.IsCreated)
return;
What is the purpose of this? My understanding is that IsCreated here is only checking for memory allocation. Is this some sort of fail-safe to garbage collection?
Context: aNativeList is a parameter being passed to a static function.
if I remember its yes memory overall by not have more than one
is this too high? I've read it shouldn't be higher than like 10-20
Hello can some one help in monetization actuall i cant put ads in my game i tried all ways possible i saw documentations videos etc but still couldnt do it if someone has done it before plz help me DM me thankyou !
I always wanted to put ads on objects in a game, like a billboard on the side of a race car game and get paid for the billboard just like it happens in real life
that is a great idea but all together i cant add any ad in my game
google mobile ads, but i havent done it myself
i followed all tutorials got the ad button screen but the ad never started nor were showed on the unity dashboard
I signed up for it and it gives you the info to do it... are you getting an error?
yeah thats the point no error followed documentation 10 times but still couldnt do it
without knowing what steps you have done and havent it hard to say what your problem is
Might want to provide some context? I see that it's part of the Code Coverage package. But what are you trying to do actually?
I'm not trying to do anything, was just wondering if this metric should be worrying
it's from the VS code metrics
Worrying in what sense?
well idk it just seems extremely high compared to what it "should" be, but this project isn't very big and it's pretty easy to maintain for me atm
what documentation or video did you watch?
but I'm seeing that anything above 50 is supposed to be like extremely urgent critical danger type stuff
I've never heard about that metric, but from a quick google it seems to be related to how difficult the code is to test. If that's something you're worried about, then it's probably serious
well it's general maintainability I guess?
unity documentation and the top 5 video search results for "how to implement ads in unity"
but alright, I just wanted to know if this is something to watch out for
how many lines of code are in each script?
thanks
It's roughly related to how likely there are to be bugs and how difficult they are to troubleshoot or detect ahead of time.
ok yeah should be fine then
are you asking me?
yeah sorry
That's quite a lot for a C# script imho
you may have come redundant stuff in your scripts????
not really
I mean a lot of it is still being built out and not properly refactored but that's fine
where did you check number from?
These numbers shouldn't be surprising if you calculate them for the whole solution imho.
oh so that's how it works?
I see
it's just that there's no option to calculate it for a single class or whatever
It defines the amount of paths in your code. Obviously, the more code you have, the more paths you will have.
Honestly, I don't think that metric is applicable to gamedev at all. Games would have complexity several levels higher than many other types of programs, so there's probably no point looking at that metric.
alright, gotcha 👍
World.GetOrCreateSystem<EndInitializationEntityCommandBufferSystem>();
Used to return a EntityCommandBufferSystem and now it returns a SystemHandle instead which does not appear to have a method to access the BufferSystem. How am I supposed to get access to it now?
For context, this is being called from SystemBase
For some reason, if I try to break a block underneath myself the game thinks I immediately looked away from the block and stops breaking it:
https://gdl.space/iwezozepuy.java
can someone help me pleae
im making axe system
collider use ontriggerstay
how can i make sure tree i cut using axe doesnt get chop more than once
since i want time frame for when can cut tree
like if its 0.2, when i click there is 0,2 seconds of detecting tree
i fugered that out, just need help with not hiting same tree twice or more
I didn't find any answer on my questions: why managers in unity are bad/good? I've heard something like "Managers are actually good if you avoid creating god objects", can someone tell the truth?
what do you mean managers
scripts like GameManager, and UIManageR?
Yeah
also, what is a god object
well
i think
u should use managers
it keeps code neat
for example
in a game with a menu, u want to be using like a UIManager
it keeps everything orgaised, and has all the references in 1 script
game managers are also good for handling things that dont really have a name
or have a name that doesnt describe itself well
What context did you hear it in and what explanation were you given?
Cache the hit tree reference and check against it.
Can't really remember, I just heard something like this
Then ignore it. If you were not given a good explanation, it was probably not a good enough of an advice.
That's still doesn't answers my question: are managers actually bad?
If you make them bad, they'll be bad, as simple as that
Managers exist to manage something
there is no one size fits all answer to this. "managers" are just a tool, and like any other tool you must use the appropriate one to solve an issue. if you use a tool that is not appropriate for what you are doing then it can be "bad". so use the right tool to get the job done.
The answer is: it depends.
Alright, thank y'all
Without trying to repeat what others have said
A note: be wary of any advice like this. "Manager" is such a vague term that this doesnt actually mean anything. People (especially beginners) will say anything is bad. I keep a list of silly things people say is bad and it includes "ints, json, if statements, reverse for loops".
don't crosspost. there are no collab posts allowed here (bot seems to be dead so it isn't linking the embed with links where you can post collab requests)
You may need to manually trigger a layout update after spawning your ui. If you disable and the immediately enable the hierarchy an update is scheduled l. It calls into this API which you can/should use explicitly https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.LayoutRebuilder.html
Ill go check it out thanks
Vector2 spawnPosition = center + new Vector2(Random.Range(-xRange, xRange), Random.Range(-zRange, zRange));
You are using a Vector2 as the spawn position so it will only randomize X and Y
Don't you want X and Z?
So it would be Vector3(..., 0, ...)
i need only x and z positions not y
Yes, and a Vector2 doesn't have a Z coordinate
The second parameter is Y
You should be using Vector3's all the way here
With the Y set to 0
i did it and it worked thanks!
hey, yesterday was the first time i've ever used classes in programming, so this is probably a stupid question, but i couldn't find anything online, so...
say you make a class and then make an instance of that class. how do you identify that class (to say, add it to a list, or change some of it's variables)?
This is a #💻┃code-beginner question.
You store it in a variable like anything else.
MyClass myInstance = new MyClass();
myInstance.Health = 100;
MyList.Add (myInstance);
alright great, mb about the channel
is there any othe way of doing a factory where u get a type and return a new class?
internal sealed class TestFactory
{
private static readonly Dictionary<Type, Type> typeMap = new()
{
{ typeof(bool), typeof(BoolConstantField) },
{ typeof(float), typeof(FloatConstantField) }
};
public static VisualElement Create1<T>()
{
if (typeMap.TryGetValue(typeof(T), out Type fieldType))
return (VisualElement)Activator.CreateInstance(fieldType);
return null;
}
public static VisualElement Create2<T>()
{
if (typeof(T) == typeof(BoolConstantField))
return new BoolConstantField();
if (typeof(T) == typeof(FloatConstantField))
return new FloatConstantField();
return null;
}
}```
You can have a ConstantField<T> and Create<T> would use reflection to find a matching one.
It's all tradeoff though, with that approach you lose the explicit relationship.
i already have both inherit to from ConstantField<T>, but idk how could reflection work in this case
Loops through all classes and check each class to see if it's inherited from ConstantField<T>.
Is there any way to have physics queries detect colliders they start in?
Oh
There's Physics.queriesHitBackfaces but it's not really what I want. I was kind of hoping for a way to do it on a singular raycast
I'm working on a game that utilizes an Alternative Controller, we're using Tanks for the players to move around.
These tanks can only move and rotate, we do not have plans on making the turret itself rotate due to the limitations of the controller.
I've been trying to find a video or some source where i can understand/adapt how to make a realistic controller for this tank. The alternative controller has two switches, where one controls the left track and the other controls the right track. as such, i need to code a movement controller that works like how a tank moves (IE: Accelerating one track and going reverse ont he other causes the tank to rotate in place)
if anyone has any good videos that describes what i want i'd appreciate it. Keep in mind we do not want the player to use one stick to move forwards and backwards, and one stick to rotate in place, i already coded that but my supervisor said that wasnt what they needed
You can use OverlapSphere with a small radius for this
This was an approach I was pretty happy with but would you have any suggestions for detecting when it's about to collide any sooner?
What I mean is the sphere was like 0.05 in radius so the spherecast was 0.049 (and then it got pushed back by 0.05)
The issue this created was you would be able to put the sphere in an object a tiny bit (by 0.001) and then it would teleport back by 0.001 to correct itself
My brain hasn't been on today I don't know what's going on
I'm not exactly sure what you mean, what is the issue vs. the behaviour you want
Showing code would be helpful too
Do you want to calculate depenetration or not?
I already have hold on
This is what I have so far
using System.Collections;
using System.Collections.Generic;
using UnityEditor.PackageManager;
using UnityEngine;
public class CollisionTest : MonoBehaviour
{
public Transform target;
private Vector3 lastPos;
public float sphereRadius;
public float precision;
public LayerMask layersToCollideWith;
void Start()
{
lastPos = transform.position;
}
void Update()
{
transform.position = target.position;
Vector3 dir = transform.position - lastPos;
float distance = dir.magnitude;
if (distance > 0)
{
if (Physics.SphereCast(lastPos, precision, dir.normalized, out RaycastHit hitInfo, distance, layersToCollideWith))
{
transform.position = hitInfo.point + hitInfo.normal * sphereRadius;
}
}
lastPos = transform.position;
}
}
precision = 0.049f
sphereRadius = 0.05f
I'll get a vid of what I mean but a bit more exaggerated
I was thinking I could maybe wrap the positioning SphereCast in a SphereCast that's the same radius as the sphere
I don't know if I explained that well
That didn't work
I still fail to see what the issue is sorry
If you look super closely you can see the sphere pentrating the cube a small bit then jumping back
Hey, is there any way to recognise when Event.modifiers and Event.keyCode don't make sense, or do I have to check it on my own?
For example, it may return Control as a modifier and LeftControl as a key, so a key binding Control + LeftControl, which doesn't make sense. The same goes for Alt + RightAlt etc.
Also, I wonder why Windows is displayed as Command + LeftApple.
Okay I don't think my approach is exactly perfect
I think I'm gonna have to rely less on a smaller SphereCast creating the friction and more creating it myself with something like ProjectOnPlane
as far as i know thats something you need to validate yourself
usually when i see modifiers implemented into a keybinding system, they use a drop down for the modifier
though of course the trade-off of that is you can't stack modifiers like shift + ctrl
but unless you're making a sim game, if you need more than 1 modifier for all of the inputs in your game you probably should consolidate
Got it, I'll create a static class with a readonly Dictionary for non-valid combinations. Thank you
So a Flag enum
yea an enum would work fine for it, i think unity might already have one but im not sure
Yes, that's the type of previously mentioned Event.modifiers
Is there any method in Unity that works like LookAt but allows us to specify which of the transform's axes to use in place of the forward axis?
what are you trying to do?
Like LookAt(transform.right, new Vector3(1,0,0), Vector3.up), Vector3.up being the optional up vector argument
Point front wheel parents to the vehicle's turning circle center
Can't use another component for this
FromToRotation might be what I need
Does physics really not have Spherecasts or Sphere overlaps?
Or am I missing something?
It definitely has both
Are you using Physics2D though?
No, this is 3D
🤔
That's a package different from UnityEngine.Physics, are you intending to use that?
There's a Collider cast, but that seems like... too generic? like using a mesh collider or something?
Yes
I haven't used that Physics package yet but I think you would just pass in a SphereCollider as an argument, no?
For ColliderCast
Does anyone know if there is a way to disable to shortcut Ctrl+W? It closes the current window and its super annoying when making a first person game. The shortcut doesnt exist in the Shortcuts tab in unity either so i have no clue why it does that
Hmmm Collider seems to be directly the type Collider instead of ICollider which SphereCollider implements, this is rather confusing, but I'm just looking through the manual right now
Maybe it's just that its this generic
Yeah, but I'm not sure why you need it to be less generic
In regular unity the different casts all ultimately return a RaycastHit anyway
By "generic" I mean that there's a single "collider cast" query instead of having a specialized spherecasting method
I know what you mean
Also since I'm talking about casting is there anything about camera casting? That's something I do use and I really don't see a comparison anywhere? Or I guess I can just manually convert the ScreenPointToRay Ray result to a Unity.Physics Ray?
What worries me is the physics though..
I guess I'd have to do two raycasts, one to get the ray from the screen point and another to get the hit in my physics world
Unless anybody knows better?
private void Awake() {
if (requiredItemType != ItemType.Any) {
OnSlotUpdated = new UnityEvent<ItemType>();
Debug.Log("Initializing event on slot"); <-- logs properly
}
}
public void UpdateUISlot(InventorySlot slot) {
Debug.Log("Updating ui slot");
if (OnSlotUpdated != null) {
OnSlotUpdated.Invoke(requiredItemType);
Debug.Log("Event is invoked"); <-- logs properly
}
//other script
private void Start() {
inventorySlotUI.OnSlotUpdated.AddListener(EquipmentUpdated);
if (inventorySlotUI.OnSlotUpdated.GetPersistentEventCount() > 0) Debug.Log("Added event successfully"); <--- doesnt log
}
private void EquipmentUpdated(ItemType type) {
Debug.Log($"Equipment Slot changed for: {type}"); <-- doesnt log
The event is not being subscribed to
This was working before I switched scenes. I verified the reference im using the add a listener to the event is correct. I feel like im missing something obvious and just need a fresh pair of eyes.
ScreenPointToRay doesn't raycast anything, just generates a ray that you can use
if (inventorySlotUI.OnSlotUpdated.GetPersistentEventCount() > 0) Debug.Log("Added event successfully"); <--- doesnt log```
Of course this doesn't log because in Awake you're doing this:
```cs
OnSlotUpdated = new UnityEvent<ItemType>();``` no?
That means it's not possible that there are any persistent listeners.
You know that listeners you add with AddListener are NOT persistent listeners, yes?
Bump
World.GetOrCreateSystem<EndInitializationEntityCommandBufferSystem>();
Used to return a EntityCommandBufferSystem and now it returns a SystemHandle instead which does not appear to have a method to access the BufferSystem. How am I supposed to get access to it now?
For context, this is being called from SystemBase
Im confused, I create the event in awake and then I subscribe to the event in the start method on another script. What do you mean it doesnt log?
The other script attempts to see the persistent listeners in the start method
Well now I know that, ill see if I can find another way to see if its subscribed properly. I don't see why the event isnt being triggered regardless
Your if statement is checking for persistent listeners. Since there are no persistent listeners and can't be at this point, it doesn't log.
If you called AddListener, it's being subscribed
Got it thank you for that. The event is also being triggered and never unsubscribed as well
if it's not triggering then you are never calling Invoke
Or you are calling Invoke on the wrong instance
Debug.Log("Updating ui slot");
if (OnSlotUpdated != null) {
OnSlotUpdated.Invoke(requiredItemType);
Debug.Log("Event is invoked"); <-- logs properly
}```
i am calling it here, it is logging event is invoked as well
possibly it's being invoked on the wrong instance then
The reference should be correct I have verified multiple times
how have you verified
Dragging and dropping it by hand. Ill do it by code as well now
the scripts exist on the same gameobject
Here's a better way to verify @devout nimbus
public void UpdateUISlot(InventorySlot slot) {
Debug.Log("Invoking event on instance " + GetInstanceID());```
```cs
inventorySlotUI.OnSlotUpdated.AddListener(EquipmentUpdated);
Debug.Log("Added listener to instance " + inventorySlotUI.GetInstanceID());```
make sure the instance IDs are the same
Thank you I will try that, busy atm but I will soon
Restarting fixed it, guess there was a bug. I dont think Ill need to try this now but thank you
Any way to force unity to render at whatever resolution I want? I can't use dynamic resolution as a bug is affecting me where I can't have a custom full screen pass render feature enabled at the same time as the dynamic resolution not being at (1, 1).
can you show a screenshot of your render texture settings? Also how are you viewing the image?
try using ARGB32 or whatever it is. Also, you didn't answer how you're viewing that image
oh sorry
using windows image viewer
pretty sure that renders gray for invisible pixels
no I think you're fine don't worry, i see it (named differently, I always forget the names of those color formats), but I think it's just that windows image viewer renders gray like that where there's invisible pixels. Like, what's it suppose to put there??
no its not I put it in the scene as an image, still has a background
@silent tapir are you using HDRP or URP
HDRP
in your render pipeline asset, what's your color buffer format set to?
@silent tapir
let me check
in that dropdown choose one that has alpha then try
yup try the other one
it was actually already on there I was looking at the wrong one
still doesn't work tho
one more thing to try.
Set the color format of the render texture to R16G16B16A16_SFLOAT In the render settings, make sure depth texture is on. Set the camera to have a solid color, then set the alpha of that color to 0.
@silent tapir
if that doesn't work then I'm out of ideas, you may need to make a shader to remove the background.
Anyone know of a way to "invert" the colliders for a 2d tilemap? I have tried adding a surrounding box collider 2d to my tilemap and then using a composite 2d collider with difference as the composite operation on both colliders but it does not seem to work at all when set to polygons mode rather than outline (the colliders just disappear in the scene view?)
SOLVED: I had to change the composite order of the Tilemap2d collider so that it was higher than my box collider
Struct packing exists, what about class packing? Is that a thing?
Maybe clarify what you mean by struct packing first.
Hello fellow humans,
Perhaps you may be able and willing to assist in my issue. I am working on a function to zoom in or out on an image based on the center point of 2 fingers touching the screen on an android device.
I can set the pivot to the point between the fingers and adjust my gameObject's scale based on the distance between the fingers however, it seems that when I set the pivot through code, it also moves my gameObject's transform away from the enter of my canvas.
Do you know how to scale a gameObject on a canvas with the scaling based on certain coordinates without the gameObject actually moving around on the canvas?
Thank you for your time.
hey all, is there anyway to programmatically add new agentTypes for the NavMeshSurface component baking? I know I can define it using the editor, but i would like to programmatically create agentTypes so i can loop through and re-bake terrains during the runtime.
Hi all, I'm updating my iOS game and I think new updates require Apple Privacy Manifest file be present in the app.
I was reading the docs regarding this and I found that Unity adds a manifest file by itself. I've verified that the third-party plugins I use have also included their own manifest files. So my question is, should I also include my own manifest file now?
Suppose I'm using PlayerPrefs. Unity has already handled it in their own manifest file, so my understanding is that I don't need to do anything since in the final privacy manifest file in the IPA everything is merged. Am I right?
If Unity really does add an Apple Privacy Manifest then it should be alright but you should check your files for that manifest. It sounds like it might be similar to the Android Permissions and the ridiculous requirements of the Google Play store that are added automatically.
In fact, you're just altogether better off contacting Unity, Apple and a lawyer about all of this as opposed to a bunch of nobodies on a messaging application.
If Unity really does add an Apple Privacy Manifest then it should be alright but you should check your files for that manifest.
They are saying that they do add the manifest file for the UnityFramework.
https://forum.unity.com/threads/apple-privacy-manifest-updates-for-unity-engine.1529026/
Introduction
At WWDC 2023 Apple announced a number of additions to its privacy program, including the introduction of Privacy Manifests.
Since then,...
Is there any way for me to subscribe to an event from all instances of a class or get the instance from a static event? I don't want to have to subscribe to each instance's event manually, but I also need a reference to the instance that invoked the event. Currently, I'm using a static event that just sends the instance as the first parameter, but I'm just wondering if there are any other ways to do it.
First use GetComponents or FindObjectsOfType then add UnityActions to them.
A static UnityEvent sounds better though
What you have currently is the way to do it
If sending in the instance as a parameter is a problem, you could also subscribe to the event using an anonymous method
Currently, I'm using a static event that just sends the instance as the first parameter
That sounds like a very typical and good way of doing it.
I have a board with Piece prefab Instantiated to fill the board. now i want them to have an idle animation which plays every x seconds. but the issue is this animation should play in sync for all gameobjects and still keep on playing if another animation plays in between at the x time given. Also no reference to these gameobjects. Can anyone lend a good approach to tackle this?
parts of this are very unclear
still keep on playing if another animation plays in between at the x time given
Are you trying to play 2 animations at once? Or do you mean another animation on a separate object? Even with the latter, its still unclear how this affects anything. You should show your code
no reference to these gameobjects
why? get the reference then or have them all reference some script managing the animation timings.
Actually i figured it out a while ago. I have a prefab which plays the same animation , only issue was when i enable the prefabs at different time, it would caused the overall animation to go out of sync of course. now i simple play the animation in a loop while having a transparent sprite which i just swap in place of enabling. Also no reference to the gameobjects since they are like 100 in number and some of them are grouped to different list. Anyways thanks for the reply.
you could also set the time of the animation state,
https://docs.unity3d.com/ScriptReference/AnimationState-time.html
oh interesting I'll have a look thanks
hi. does anyone know how to handle localization for numbers? I want to eventually convert the int into a string that's localized by the Unity's localization system
in case relevant, here's the full context. the LocalizeStringEvent is a built-in component that has a StringReference and gives us a nice inspector for subscribing string properties to listen to this (TMP_Text.text for example)
only solution that comes to my mind is creating a new entry for integers, passing in an integer variable alone, and then set it from the code using
var variable = localizeStringEvent.StringReference[variableName] as IntVariable;
Assert.IsNotNull(variable, $"variable \"{variableName}\" was not an integer");
variable.Value = amount;
but come on 🥲
so you want different int values for each language or do you just want to visually localize numbers to other letter sets or how you call it like mandarin, katakana etc
Finally solved it!
is there a way to detect an intersect between an overlapbox and a raycast?
No. They don't physically exist at the same time.
is there another way to do something similar? im just looking to use a custom collision detection system
Well, you're already relying on unity physics with the queries(raycast and overlap), so you can't really say that it's "custom". If you want to use these queries, you'll need to have colliders to use these queries against.
The only other option is that you implement a whole custom physics system from scratch with your own queries.
Maybe describe what you're trying to do, as a game mechanic. It sounds like you're just using a overlap box instead of a box collider
theres no game mechanic im tryna achieve, but i feel like only having a couple functions to catch collisions on the default collider isnt enough. thats all really (and i was just interested if it would even be possible)
Well the question above wasnt implying any new functionality. You essentially asked if a raycast could detect an overlapbox. An overlap box can easily be represented by a box collider. A raycast can detect a box collider
https://docs.unity3d.com/ScriptReference/Bounds.IntersectRay.html
There is also this, if you specifically dont want a collider in scene. But this is completely unrelated to an overlap box
it was mostly just the interest of doing a collision system which is not the default one. By "isn't enough" i was referring to the colliders only having the OnEnter, OnExit and onStay function. i tried using an overlapbox (and raycasts for bullets) but as it turns out its not possible
What's the issue with having only these 3 functions? It should be enough even if there was only 2: on enter and exit. What else do you need and why?
Yea idk it's hard to really say anything because it sounds like 2 things
1: you arent familiar with how physics works in unity (thus the overlapbox being used in the first place)
2: want extra functions because of number 1
When theres something concrete you actually need to solve, then worry about adding functionality. But having no game mechanic you're trying to achieve and just wanting more functionality for the sake of it isnt a good combination
alright, i see. thank you
I have a menu like that which let's you select the level you want to play, right now I have to scroll using scrollwheel but it's gonna be an android game... So how can I make it scrollable with fingers?
EDIT: nvm I found https://forum.unity.com/threads/camera-drag-to-scroll-for-3d-games.53244/
My requirement is
- if i drag on the iphone's surface with a finger than i should be able to scroll the camera in such a way that the initial touch...
I have a weird bug in my unity editor. I want to delete my prefab and if I hit delete, it reappears after 1 second. The prafab isn't commited to unity version control yet, and I haven't removed any folder, just duplicated this prefab as a backup from another prefab, but now i can't delete the backup prefab. Is there any solution for this?
you mean delete from the assets folder?
sorry yes, i mean that
There's no reason the asset should be reappearing automatically. That sounds like the result of some external program. For example OneDrive, or Google Drive, or DropBox or something along those lines.
i use only unity version control, the folder also haven't been opened in any third party application 😦
i restarted windows, but i still can't delete it, the delete works for other prefabs
I have a game that needs every effect to be unique, and I want like 50 of them. A "Subject" NPC has a list of effects applied, and this is changes in-game with random effects. What is the best way to store these effects? I had an abstract BaseEffect class and then derived classes for each effect, but since the base class is abstract I can't have an array of that
ScriptableObjects wouldn't (to my knowledge) let me have the custom ApplyEffect logic for each separate effect unless I had a new scriptable object type for each effect, which would get cluttered fast and seems kind of useless
How can I make some borders not thicker than eachother its annoying, idk how to fix it, resolution scaling maybe?
If your render resolution matched up with the sizes of those ui elements?
Yeah, Unity doesn't do it nicely
Resolution scaling will make it more likely for this issue to appear. In order to maintain the constant proportions your grid size has to have a size equal to: constant * (cellSize * cellCount + cellOutlineWidth * (cellCount + 1)). If it's not exactly fitting this formula, then the issue is likely to be visible.
You may also consider adding the pixel perfect camera, according to your game
how shall I check
if you have to check then it isn’t and that’s the reason why. See the other comments for solutions.
okay
Is it really possible to make a native app for different gaming apk builds.
Single native app downloading different gaming apk resources and opening them.
is there a way to have visual studio analyze and correct my tags? 🤔
I mean, unity has a list of tags but I have to write a string... I could make a typo... isn't there an enum somewhere or something?
(is there a better tagging alternative?)
There is no enum, no - tags kind of suck in general. I think there is an undocumented/unsupported internal collection, but best not to rely on it.
Scripts themselves can act as a tag alternative though
The latter.
Also didn't know katakana had different number letters. Come to think of it, I've never encountered a non-Latin numerical system in Japanese media (even in the textbook I'm reading!)
Yeah tags being essentially unchecked magic strings is definitely one of the reasons that it sucks.
Oh right! Seems they use the kanji letters for the numbers for traditional formats! So like 一ニ三四...