#archived-code-general
1 messages ยท Page 29 of 1
If you have a Top down 30 degree camera following a character in game. And you want the camera to lock it's rotation even when the character changes it's rotation; you can either unparent it from the character and set the location of the camera to the location of the player. Or you can keep it as a child, and set the camera's rotation on update.
My issue, is that I want to rotate the camera around the character while the character is moving (rotating).
I'm using RotateAround
transform.RotateAround(MainPlayerCharacter_Reference.transform.position, Vector3.up, -targetAngle);
The way I see how I would go about doing this would be:
- Unparented camera - Get location of character and offset it somehow while the camera is rotating, so that it stays locked to the player while moving.
- Parented camera - Get the Y rotation in euler angles of the player character, and subtract it from the camera's rotation, so that the camera can rotate around the character freely while keeping it's position locked on the character.
Don't really get how to do 1, and 2 is super buggy to convert Quaternion to Euler and back it seems. Any help on this would be much appreciated.
Hello, I'm not sure if I'm on the right channel, if not feel free to redirect me.
I'm trying to convert 3D models to pixel art, I'm using a render texture to display the model with a low resolution (my RT is of size 64x64).
So far everything is working except that I now, made a system that generate a texture, and allow my to draw on it, this texture should be applied to the generated spritesheet created from the RT.
To map my texture, I made a vertex shader that set the colors of the vertices, given their positions in the world, where x -> black to red, y -> black to green, z -> black to blue, it gives me a color space in a 3 dimensional space. Once it's done I look up each pixels of the texture I want to apply, and compare them with each pixel of the generated spritessheet frames, if the color matches I apply the color pixel from my texture.
Now the problem is that the render texture doesn't always display the exact colors of the pixels I'm trying to apply, if my spriteSheet is animated, it blends some colors instead of displaying either on or the other, so my question is, is there a way to make my render texture display the exact colors of the model and not have them blended?
if you look at the face, and the symbol drawn on the torso, it looks jittery, and I feel like it's caused by the render texture blending in two pixels, if you need more informations let my know
A better version of the end result :
thanks
I have another issue where I have a text over a button and the button isnt being pressed because of the text in the way. Is there a way to make it so the click goes through the text?
I'm creating a top-down 2D game and trying to create a shotgun. It was not quite succesfull on this point. I only have the script to spawn 10 bullets, but they spawn in the players rotation, what's good, but is there an easy way to spread the bullets in a random range of (-10,10)?
{
Instantiate(normalBullet, basicSpawn.transform.position, basicSpawn.transform.rotation);
}
Since I can't find a good tuto for 2D who has this and you can't sum or sub Quaternion vars, do I have no idea how to create it.
for (var i = 0; i < 10; i++)
{
float angleDiff = i - 5;
Instantiate(normalBullet, basicSpawn.transform.position, basicSpawn.transform.rotation * Quaternion.Euler(0, 0, angleDiff));
}```
Oh really thanks! I was searching at this for 2 hours.
how do i lerp emission color change? This is not working
the lerp for material1 is workig but for material2 not
first configure your IDE
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i did now
there is no error
it's changing to the material2.color at the beginning but then stays at it
so the emission color is changing to the basecolor of the same material
what are the values you're getting
ah i figured it out. I am lerping the emission color with the basecolor but the basecolor isn't lerped that's why it's not changing
was about to say
also might want to look into this
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
when i changed it to material1.color it worked because the first should actually change the basecolor
ya thanks
what is a good line limit to have per script?
so i know the basic OnCollisionEnter and -Exit methods. The character controller doesnt trigger that according to the docs. How can i detect in a script of a gameobject when the player "collides". From the player sides there is the OnControllerColliderHit() method but i want to check from the other gameobject
Can someone please tell me why I am getting an object instance error?
My Script (The script that creates the error): https://pastebin.com/jZkntN8c
The script I'm trying to use the "AddMesh" function from: https://pastebin.com/UDPtFQKg
Error: NullReferenceException: Object reference not set to an instance of an object
WaterVolume.WaterVolume.AddMesh (UnityEngine.GameObject obj) (at Assets/WaterVolume/Scripts/WaterVolume.cs:240)
doggo.Start () (at Assets/WaterVolume/doggo.cs:12)
It does print "Added" from the addmesh function, but then gives the error
the gameObject you pass in the function is probably null, do a Debug.Log on your gameObject
meshCache.AddMesh(obj); the only thing that can give you a NRE is meshCache, so that's null.
Meaning meshCache is null and I'd need to create a new meshCache within the "doggo.cs"?
on what line do you get the error originally? Your custom script?
Its GameObject.Find("Plane2"), right?
Yes, line 12 wv.AddMesh(GameObject.Find("Plane2"));
You should check against null if you use Find (which you should not if possible), is it null maybe?
ok, so I changed it to:
`
public class doggo : MonoBehaviour
{
WaterVolume.WaterVolume wv;
private void Start()
{
wv = new WaterVolume.WaterVolume();
if(GameObject.Find("Plane2") != null)
{
wv.AddMesh(GameObject.Find("Plane2"));
}
else
{
print("The plane is null");
}
}
}
`
and it does not print "The plane is null". But the Object Instance error still occurs
oh
Fast, before we throw that code command! ๐
your meshCache is initialized in the awake method and you call the function in the start method
the start Method is always called after the awake method iirc which means your meshCache isn't initialized before you call that method
Oh wait, you are trying to create a watervolume monobehaviour with a new function, thats not gonna work
your wv is null Id say
okay so I changed Start() to Awake() and also did a check if WV is null. It says it is null! But how could that be fixed? I need to use the AddMesh function from that script.
MonoBehaviour needs to be treated as component! So if you want a new watervolume, you gotta add it as a component
Ohhh
Edit: Fixed, thanks for the help :D!
Not sure the class you are using is meant to be created at runtime multiple times, but thats something for you to test ๐
there would be an instance if it didn't
If we expect this script to be bug free, I agree ๐ but good point
and instead of wv = new WaterVolume.WaterVolume(); you want to use GetComponent<>() to get the reference of that script
any of you could help me for a Render Texture by any means?
you know how to ask a question, i am sure ๐
I did
where? I guess I missed it then
scroll up a little, there is a gif with a multi colored character, that's my post
Oh, you want to have the opposite of anti aliasing here, right?
Well yes, in my Rendertexture I configured the anti aliasing to be none
yet some colors still blend
I guess you have to step the colors to match your color palette
what do you mean by step?
like a step node, where you separate a vector 1 range to a defined step. so for example a color value of 255 gets "stepped" into 16 steps instead.
But this really depends on your colors tho. If you allow any colors, its impossible to clamp the values in any handleable way
The problem is, the downsizing already does what you want. you cant guarantee a pixel to be a color. Or does your texture look different from the rendertexture?
yeah I figured, I tried to create the color space for each part of my model individually but it gives, just slightly better results if any
even if that pixel is a Color32? so it's defined between integers of 0-255 instead of a float of 0 - 1
0-1 is still floats, so that wont change much I guess.
Your downsize will decide, like seen in the face, if its black or not, thats all you get no matter the actual steps. Thats the downside of downsizing vs "real" pixel art
no yeah I meant that I went from Color to Color32 to restrict the color range a little
Your best bet here would be, do not use 1 pixel lines in your design
The less resolution you got, the less details you should add, and that face and icon on the middle is just too much for 64x64
how can i set a fix emission intensity? When lerping the emissions color it always changes too
definetly, but I feel like there is a way to do that, isn't there just a way to prevent a render texture from blending the colors? just gives either one or the other color, even if it displaces the pixels, I'd be fine with that
Oh I mean, you could use a custom material and do it shaderwise here
So you could use shadergraph and the step node to reduce the colors for example: https://docs.unity3d.com/Packages/com.unity.shadergraph@6.9/manual/Step-Node.html
or up the contrast or or or
but that wouldn't influence the render texture would it?
Something is showing your render texture, right? That component should be able to hold a material?
I guess you are right
what if I also added a 3 dimensionnal grey scale when computing the color for each vertex?
as far as I'm concerned white and black aren't showing that much, if at all on this model
try to step the colors and then greyscale them by setting the saturation down for example. Dont know how you set the colors right now at all ๐
Like so, I simply have a vertex shader, I encapsulate the bounds of every renderers in my model and then evaluate the lerped value of a worldPoint given the min and max bounds
I used 3 different gradients to represent the 3 position axis because I wanted to see if there was a better color set that RGB
Okay, understand that code part. so you could just lerp from black to white to get greyscale here, right?
yep
the thing is, among all the colors that the vertices will display, there is a lot of colors that are not used because no vertices get these coordinates
I might wanna use that
But you clamp the color range to the vertices already, so all colors hsould be used somehow?
nope here is a quick drawing to make it clear :
Maybe I can try to use those colors to make the difference between the colors more pronounced
ah you take the box bounds, yeah, makes sense.
how can I get the mouse position while cursor is locked. Nothing online ๐ฆ
Input.mousePosition not working?
not while cursor locked is on no
if the cursor is locked your cusor is always placed at the center of your window
Oh, well, than you gotta get the delta vector, what input system?
i can get the delta, but how can i get the mouse position from that? Im using the mouse position to compare and get angle from a UI element
wait, you cant move your mouse but want to get values from a none moving mouse? I guess you undersatnd the confusion here
How would the UI behave. Depending on your mouse or just like the rotation of your camera?
lol I will explain. Its a first person game so the cursor is hidden/locked, but when you interact with someone a radial menu comes up. And i want the selected option on that menu to be in the direction of where the mouse is. actually i guess I could use delta tbh
Anyone have any experience with VContainer? ๐ฅฒ
for me i just looked up on youtube 'unity gta weapon wheel' and did my emote-wheel thing based on that
thanks
np
seems like putting a greyScale is working better, it still didn't finish to create all the frames but I'll wait and see
Is there a way to clear RenderTexture without camera?
My game literally has only UI
UI toolkit
what you mean by clear rendertexture?
if there are no cameras in scene, whatever was drawn will stay on screen
without any cleanup
well, without any camera, how do you think unity will render anything at all?
my UI is drawn with UITK
So why not just use a camera with nothing to see in clear flags, so its empty but still rendering?
do I pick nothing or everything?
nothing
yw ๐
How do i typecheck an asset?
if (assetType is GenericScriptableTypeRef)
{ do stuff }```
rider tells me the expression is never true
what am i missing
GetMainAssetTypeAtPath returns Type, so you need to check like this
if (assetType == typeof(GenericScriptableTypeRef))
If there was an instance of GenericScriptableTypeRef in that variable, it would have worked with is.
ah ok but my problem is that the assetTypes i want to process inherit from GenericScriptableTypeRef. typeof does an exact typecheck which would always be false.
Ah, time to whip out some Reflection then, typeof(GenericScriptableRef).IsAssignableFrom(assetType)
thank you! exactly what i needed
Is it possible to get an animation's exact state, send the data over a network and recreate the pose exactly?
I've been trying to figure out how to accomplish this, especially when the animations are blended
when I tried it you had to send multiple states
you get multiple states from the animator
Does each blended animation have it's own "time" as well?
yeah
Ok cool
@lyric wadiHow do you go about actually reconstructing the animation on the server though?
something like this?
I wonder if you can just send the state hash of the animator instead then...
trying to remember it was a couple years ago
no worries
I'm starting with localization and I need to do this, but with script... how can I do this?
Looks like an UnityEvent, which you can add listeners at runtime with UpdateString.AddListener. They won't show up in the inspector.
hi yall, I'm having an issue with setting the screen resolution/windowed mode - these functions are both being called from dropdown menus, and I've confirmed that the relevant functions/switch cases are being called (at least in editor).
public void SetResolution(int resolutionIndex)
{
_resolutionIndex = resolutionIndex;
Debug.Log("Setting Resolution");
Screen.SetResolution(_resolutions[_resolutionIndex].width, _resolutions[_resolutionIndex].height, _currentFullscreenMode);
}
public void SetFullscreenMode(int index)
{
switch (index)
{
case 0:
_currentFullscreenMode = FullScreenMode.ExclusiveFullScreen;
break;
case 1:
_currentFullscreenMode = FullScreenMode.FullScreenWindow;
Screen.fullScreen = false;
break;
case 2:
_currentFullscreenMode = FullScreenMode.Windowed;
Screen.fullScreen = false;
break;
}
Screen.SetResolution(_resolutions[_resolutionIndex].width, _resolutions[_resolutionIndex].height, _currentFullscreenMode);
}
I'm not really sure what I could be missing - nothing at all seems to happen in build
Debug it in a build.๐คทโโ๏ธ
Would I ask here for help on camera/player movement and my associated script or is that something for #๐ฑ๏ธโinput-system?
Probably here, unless it's explicitly related to the new input system
Cool, then here we go. ๐
Here's a video of what my below script produces. I'm trying to add roll to my player/camera along the z axis (which... works lol) but not entirely.
It seems the orientation of the x and y axes are locked or something which makes movement very difficult if the current value for the z axis is anything other than zero. Any ideas or advice on how to fix this would be greatly appreciated.
Here's my camera movement script.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
[SerializeField] private Vector2 sensitivity;
[Tooltip("The rotation acceleration, in degrees / second")]
[SerializeField] private Vector2 acceleration;
[SerializeField] private float zAcceleration;
[Tooltip("The period to wait until resetting the input value. Set this as low as possible, without encountering stuttering")]
[SerializeField] private float inputLagPeriod;
private Vector3 rotation; // The current rotation, in degrees
private Vector3 velocity; // The current rotation velocity, in degrees
private Vector2 lastInputEvent; // The last received non-zero input value
private float inputLagTimer; // The time since the last received non-zero input value
private Vector2 GetInput()
{
// Add to the lag timer
inputLagTimer += Time.deltaTime;
// Get the input vector. This can be changed to work with the new input system or even touch controls
Vector2 input = new Vector2(
Input.GetAxis("Mouse X"),
Input.GetAxis("Mouse Y")
);
if ((Mathf.Approximately(0, input.x) && Mathf.Approximately(0, input.y)) == false || inputLagTimer >= inputLagPeriod)
{
lastInputEvent = input;
inputLagTimer = 0;
}
return lastInputEvent;
}
private void Update()
{
// The wanted velocity is the current input scaled by the sensitivity
// This is also the maximum velocity
Vector2 wantedVelocity = GetInput() * sensitivity;
// Calculate new rotation
velocity = new Vector3(
Mathf.MoveTowards(velocity.x, wantedVelocity.x, acceleration.x * Time.deltaTime),
Mathf.MoveTowards(velocity.y, wantedVelocity.y, acceleration.y * Time.deltaTime),
velocity.z
);
rotation += velocity * Time.deltaTime;
// Check for "q" and "e" inputs
float zInput = 0f;
if (Input.GetKey(KeyCode.Q))
{
zInput = 1f;
}
if (Input.GetKey(KeyCode.E))
{
zInput = -1f;
}
velocity.z = Mathf.MoveTowards(velocity.z, zInput * zAcceleration, zAcceleration * Time.deltaTime);
rotation.z += velocity.z * Time.deltaTime;
// Convert the rotation to euler angles
transform.localEulerAngles = new Vector3(rotation.y, rotation.x, rotation.z);
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
transform.position += transform.forward * vertical * 0.5f;
transform.position += transform.right * horizontal * 0.5f;
}
}
hey, so maybe im looking in wrong places but i honestly cant find a proper solution, so basically i have a bird gameobject, and a wing gameobject as its child. i basically just want for wing animation to play when i press space and for the bird animation to play when the bool is set to true. i have a seperate script with settriggers etc. so basically now what do i put where, because putting animator and animatorscript components to both of them separately simply breaks the whole bird
Hey I'm using some code to create text and I rescale it's bounding box, but for some reason it's not scaling it from the center.
box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
text.rectTransform.sizeDelta = new Vector2(text.rectTransform.sizeDelta.x + 40.22f, 40.22f * 2f);
box.size = new Vector2(text.rectTransform.sizeDelta.x, 40.22f);
But the pivot is by default on 0.5, so it should scale it from the center
And if I do it manually through the inspector, it does scale it from the center, so I'm no sure why the code doesn't and what I can do to fix that
howdy, may i request some consultation and guideness from the unity experts
sure
I'm also going to ask my question
how can I implement move_and_slide with navagent as in godot?
key being the this-normal*this.dot(normal) line
don't really understand the math here
its c++ so theres use of pointers i dont know if you probably already knew that
I made this desmos thingy for it: https://www.desmos.com/calculator/tptotlqmho
But like, that does not look like sliding...
yep, I'm purely concerned with the math
roger roger, i sugg at maff
looks like it takes the normal and multiplies it by the dot product (could be totally wrong ahah)
yes that is literally what it does
i cant help sorry ๐ฆ
any one else?
i dont wanna post something an block your question so ill wait
no go ahead
i have a tile perlin world and im generating a minimap using setpixel and using ongui. ive got it to generate the world and move with the player but the minimap just wraps and doesnt generate the rest of the world like the world generating code. i think i just dont understand and am trying to force something that cant generate like that computationally quickly. updating it in the update method just chokes hard
seems kinda vague?
it just tears and repeats rather than constantly generating
sorry i am kinda a noob
vague will be my lack of experience in what to even explain cos i dont know enough to know exactly whats wrong xD
"doesn't generate the rest of the world" you mean it only generates, e.g. coords within (-100, -100) (100,100)?
I'm used to working with a 2021 version of unity, but a friend invited me to work on 2022 unity, and it seems a few things have changed. I can't find how you bake a navmesh in this version, There should be a "bake" tab at the top, but it isn't there.
I'm used to it looking something like this
With a bake and object tab as well
Try the 3 dots top right?
i guess thats the right way to put it
rather than wrap around it should continue to generate the next coordinates
Add tab doesn't add anything useful
your code then?
@compact verge I don't think you need to bake
I did but all the answers are from 2020
Then how do you create a navmesh
shall i paste the whole code block?
sure
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
worldSize?
changing that doesnt seem to matter i get the same result
ive tried moving things around, in start and update etc but it always does this
u can see the tearing where it repeats
@compact verge this should help https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.0/manual/NavMeshSurface.html
That doesn't seem to be wrapping oke?
Are you sure it is?
Yeah I've used navmeshsurface a lot in the past, but there is also a much simplier way
But ig unity removed that
hm? com.unity.ai.navigation is the new stuff, not the old
this + cross section just repeats
its visible if i move
its the same image tiled infinitely xD
im trying to get it to just keep drawing based on the new x and y
I guess I just don't know the math
it might be a limitation with setpixel and ongui but i cant figure it out
then i gotta think of alternatives
but ive seen it in say shadergraph, i can scroll through a 2d perlin noise map quite easily
infinite procedural yadayada
Is there at least a way I can get the next frame step of a navmeshagent and decide whether I want to do it or not?
I want to load assets dynamically at runtime
Any recommended plugins for it?
Addressables.
ewww apparently navmeshagents will autobreak 100-0 once they hit their target
even if they have poor acceleration
disgusting
For anyone familiar with LeanTween, is there a clean way to pass a LTDescr as an argument? I thought I was on the right track with my current implementation, but I'm getting some unexpected results. When opening the panel, the animation will play the first time and never again. Closing the panel doesn't seem to do anything. If I use the default tween, opening and closing both work fine.
@devout wigeon I had that problem with LeanTween and it isn't related to your code because I wasn't using it that way. I never found a good answer and just switched to DOTween
Hmm. Well, that's not a good sign. I'm still going to do a bit more digging before giving up because I'm in pretty deep with LeanTween.
I'm building a simple FPS style character and finally got jumping to work properly where the player can't move in midair. When I land, though, my current movement resets instantly, e.g. if I'm falling sideways and hold w, when I land I'll instantly stop moving sideways and immediately go forward. How should I make this a gradual de/acceleration when I land?
cC is my character controller.
if (cC.isGrounded) { // Only able to move while touching the ground
move = transform.rotation * (new Vector3( // Get inputs
Input.GetAxis("Horizontal"),
0,
Input.GetAxis("Vertical")
));
if (Input.GetButton("Jump")) movementY = jumpSpeed; // Jump
else movementY = 0;
} else movementY -= gravity * Time.deltaTime; // Fall when in the air
move.y = movementY;
cC.Move(move * Time.deltaTime);
For what it's worth, do you have a quick example of passing a DOTween in a similar way?
you would need to implement a concept of "momentum" into your code
and have your input affect the momentum gradually instead of instantly
might be easier to just use a Rigidbody based controller at that point since it has velocity built in
It looks like your code is effectively just forcing a close->open or an open->close transition regardless of the current state? I don't see what that wouldn't be feasible with DOTween. It gives you a Tweener object that can me manipulated much like LTDesc objects.
Hang loose for a minute.
The main question I had was what part of DOTween maps to LTDescr. Looks like Tweener is what I need. I appreciate it though! No need to go out of your way.
Keep this bookmarked http://dotween.demigiant.com/documentation.php
DOTween is the evolution of HOTween, a Unity Tween Engine
Their APIs are very similar but the terminology is just different enough to trip you up
Thanks for the help! I appreciate it. Going to try it out and see if I want to make the switch. Been using LeanTween for a few years but it looks like it's slowly dying.
I like LT but after that bug popped up and I couldn't figure it out I figured it is worth it to just bail instead of wasting more time. All tween libraries are similar enough that its easy to move over.
Yeah, just last week I ran into an inexplicable issue where the depreciated tween.cancel() worked but the newer LeanTween.cancel(tween) didn't. Took a while to work that one out. Seems like it might be time for a change.
Whenever I try to open any windows in unity, it doesn't open. I'm trying to open preferences, but after countless attempts it still doesn't do anything when I click on it. None of the other windows open either. I've tried closing and opening unity and it still doesn't work. This problem only occurs on my laptop (which I'm using right now) but not on my PC for some reason. Any help would be appreciated.
ok i have two problems , the first is that I made a linux server build, the application.quit ISN'T working.. I am using System.Diagnostics.Process.GetCurrentProcess().Kill();
I want to know would that cause a problem to my game or would there be a risk of anything??
Try resetting your layout settings by clicking the layout drop-down in the top right of the editor
my 2nd problem is with unity webgl builds... I am using the Application.OpenURL("https://..."); and it is also not working... can osmeone help me
what is the .../%22 part supposed to mean?
also aren't you missing a " in the end?
(just wanna make sure it's pseudocode lol)
nothing it is just that I hid my link... wrote random characters
no no I am sure I didn't miss the other " in my code
just type Application.OpenURL(..) next time :p
Application.OpenURL should work in WebGL, BUT
you'd be better off using javascript, with Application.ExternalEval
can someone help me? Microphone.devices is empty, and I cant figure out why. unity audio is NOT disabled, ive triple checked
Application.ExternalEval("window.open('http://www.google.com');");
not a web gl build
what is Microphone?
do you mean something like
"Application.ExternalEval("window.open("..")");"
its a unity class
oh
it lets you access the system microphone
ah, never heard of it.. I'd use the system classes if available
cant, needs to be cross platform
thank you i will try it
mind you should add the #IF UNITY_WEBGL preprocessor to it
it is saying it is obsolete ... what should I look for to make this work without using obsolete classes
in PC builds, you'd rather use the OpenURL
well, OpenURL SHOULD work
just maybe not open it in new tab (but maybe they fixed this from what I read)
so maybe it's your ad blocker settings?
I want to open it in the same tab... it is not working .. I am going to try and put even in the build a debug text
there are no ad blockers used now
yes
just a second
if you dont mind we're going to do 1 test in 10 mins... I put a debug text...i will make sure that the condition leading to goign to the other webpage is happening
sure yeah
but just found out that OpenURL now doesn't work in an old project in which it used to
tried in both chrome, firefox, and msedge
yw
ok, so. couple requirements there:
- Unity should be allowed to use microphone (there's an option somewhere in windows settings)
- Device should be available//not in use by another app
um.. restart the editor? ๐
thats what im gonna try next
I wanted to suggest enabling the 'allow apps to take control of this device' option, but since unity accessed it it should already be enabled -- wouldn't hurt to double check though
this?
no go
restart time
i should also clarify, im not looking for a specific device, i jsut want any devices at all
that did something!
no longer telling me theres no mic
now the editor crashes
ima try agian jsut to confirm
OK
mic is now detected
idk wtf that was, but thank you for your help
np lol
it's possible the devices are only scanned on editor open, so if you opened the editor while they were unplugged or in use they wouldn't get registered
hmm, interesting
I assume the built-in Microphone class is not a very popular API, so yeah I'd be reluctant to go with it either way
i need a cross platform way tio detect if the mic is above a certain level
it cant override unity audio like fmod
I've seen a number of voice-related APIs in many languages or whatnot, so if you don't care about WebGL might wanna go for it
alright
im trying to write a function to open audio files from a .zip file
i have this code that makes a DeflateStream that presumable contains the data, but i dont know how to convert it to an audioClip
public AudioClip LoadAudioFromZip(string zipFilePath, string audioFileName)
{
// Open the zip file
using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
{
// Find the audio file in the zip archive
ZipArchiveEntry audioFileEntry = archive.GetEntry(audioFileName);
// Check if the audio file was found
if (audioFileEntry == null)
{
Debug.LogError("Audio file not found in zip archive: " + audioFileName);
return null;
}
Debug.Log(audioFileEntry.Name);
Debug.Log(audioFileEntry.Open());
// Convert to Audioclip?
}
}
i want to make a 2d tower defense game, but how can i make my turret target the first enemy? i have no idea, i don't need code but help to understand the algorithm
the range of the turret is a 2d circle collider (trigger)
when i made a tower defence game i had a list of all active enemies then got all enemies in tower range then targeted the first one on the enemy list
oh yes, and then search for the smallest number for each enemy in the range
of the turret
in my webgl app the fullscreen button wont work.. any idea why that might be
but what if there is a faster enemy? or a slower one
i could do that a faster enemy is a priority but that could cause problems
for example it will ignore other enemies that are closer to my base
they you will need to make a function to sort the list of enemies, i presume your enemies are traveling along a list of points?
yes, i still need to do that but i already did in another game
the enemies will follow a path made of a list of positions or something like that
but if i need to sort the list, how can i make the faster enemy place in his current "location" and not too low or high in the list
sort enemies by their target point, then sub sort by their distance from that point
i have searched online but i cannot find anything, can this video help? https://www.youtube.com/watch?v=9gAHZGArDgU
i have not watched that video but maybe it could help you
Its different because a .zip gives me a Stream not just raw file data
what if you move the audio file in appdata folder of the game, and then use that file?
im using them for voiceover/subtitle data, so the .zip will have hundreds of soundclips so having them stored as open data would be less efficient
yes, you are right
This is your editor giving a warning, not Unity
So this code is fine
Your editor is just clueless about it
I'm sure it can be supressed somehow
I see. Is there something I can do to guarantee my async method is awaited before Update() is called?
I don't think there is without some hacky workarounds like disabilng the object
Idk what UniTaskVoid is
But Unity is not gonna wait for an async method before calling the next tick
So If you specifically want an async method to finish before calling the next Update, the actual update method should check if the method finished
Is this what the return type is? https://cysharp.github.io/UniTask/api/Cysharp.Threading.Tasks.UniTask.html @slow crag
Cause I can't find UnitaskVoid
This has a status property, returning this: https://cysharp.github.io/UniTask/api/Cysharp.Threading.Tasks.UniTaskStatus.html
So you should check if it returns anything but pending, and then you should handle the result should it have faulted
This is how it works with actual Tasks anyway
yeah, I'm just doing this for now:
private async UniTaskVoid Start()
{
// Disable Update() until all the managers are initialized
enabled = false;
DefManager = new DefManager();
await DefManager.LoadDefs();
InitializeManagers();
StartNewGame();
}
as for this, it seems like it, though I think it should be smart enough to recogniye. For now I just suppressed it but it still bothers me xD
Works too
Give me 1 sec and I'll give an example on what I mean once I get back to my pc
I'm pretty sure I understand what you meant but it doesn't feel as good as this "workaround"
How can I make it so I can scale this from the center within the code? The pivot is already 0.5 but adjusting the sizeDelta within the code doesn't scale it from the center
I need it to be bigger because the IDragHandler ignores BoxColliders
If I can make the IDragHandler unignore BoxColliders, that'd work too. But you probably can't really do that
Good morning everyone. Is it possible to switch or if statement over a generic T value? I am trying to have one function handling different lists. So I want to pass in json data, the target list and also the type. Can I get the type from the target list or just use a third param to pass in the desired type?
private void RecievedDataHandle<T>(string data, List<T> targetList) where T: JsonAttributes
{
var Object = JsonConvert.DeserializeObject<CMSJson>(data);
if (Object != null)
foreach (var d in Object.data)
if (d != null)
{
///Switch here somehow to get myDesiredType
targetList.Add(d.myDesiredType as T);
}
}
Are there always a set amount of types it can be?
Yes, I have three, just do not want to have three voids for that ๐
Can anyone help me with this?
I have a class that contains a list called itemData whose values are defined in the inspector. On a separate script I want to have a dropdown in the inspector that lets you select one of the values contained in the itemData list from the previous class. How do i go about doing that?
If you've three can't you just "hard code" the three variants in it?
So using a third parameter you mean?
how do I stop the cineamchine camera dragging behind my camera
oh ok
How do I make a separate tile have some functionality? Like the question mark tiles from mario, when you hit them with your head from the bottom, they spawn a mushroom at the top of themselves and the tile's sprite changes
In the end, I just compare against typeof(T).ToString() ๐ As it will never be different from now on, no need to make it full dynamic. thanks ๐
Ah okay, nice
Sorry for not answering I was kinda looking up how switch cases work for switching types again heh
yeah, you cant really switch types directly ๐ I think someone here had that conversation yesterday too ๐
Yeah exactly, since the value has to be a constant in switch cases, so I needed to look up how you can do it heh
Switch cases are great but they can also be limiting in some areas
I would have been fine with a simple if T is myClass, but thats not working either in my generic usecase. But yeah, not really useful to work more on that as it is a project that will be fixed to this dataset anyway ๐
Yeah no need to spend a lot of time making it dynamic if it'll never change anyway
Though that being said, if you ever just don't have anything to do, you can just (try to) make it dynamic for experience :P
I find experimenting one of the most fun things in programming
If it wasnt for a client, I would make this work at some point ๐ But he wont pay my testing around I guess ๐
Haha, that's understandable :p
On another note, do you've any idea as for this?
Let me check
Do you want to scale the recttransform or just the mesh when you changing the text?
Just the recttransform, I want the "bounding box" to be bigger so the IDragHandler effects a larger area
It's quite funny because now I use IDragHandler instead of IPointerEvent, which now I just have a different issue, I'm just trading a problem for another problem heh
How about giving it a transparent image as child that is offset to like -20 on each side?
-20 is like random ๐
Preferably I'd rather not have to add extra components to it just to get the bounding box right
Like it should be simple to do in code, but for some reason it just doesn't recognize it's supposed to resize from the center
Whilst when you do it manually in the inspector it does
Can you show your inspector of how you do it there?
Or rather, from where is it scaling if you say, its not from the center?
box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
text.rectTransform.sizeDelta = new Vector2(text.rectTransform.sizeDelta.x, 40.22f);
box.size = new Vector2(text.rectTransform.sizeDelta.x + 40.22f, 40.22f * 2f);
Well that's how I do it through the code, and sizeDelta is the same as the width and the height
So I adjust the width and the height in the inspector and that does center it from the middle
I do see now that the alignment is bottom corner again now though which is weird
Okay now both don't scale from the center whilst yesterday it did ;-;
The problem with your solution is that you're not handling errors, though
You gotta check SetSizeWithAnchors I think ๐
Hm lemme see
Ty
That doesn't appear to be working
Well I mean it does, but still not from the center
Is it changing the anchoring again?
box.size = text.rectTransform.sizeDelta = text.GetPreferredValues();
text.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 40.22f * 2);
anchoring is 0.5 on everything
well, thats not what we set yesterday, did we?
And this looks centered to me. YOu mean the text is not centered vertically?
The bounding box is larger on the bottom than on the top
The bounding box should be on the center point of the text, so that it's the same above and below
the bounding box is as expected, but your text is on vertically centered in the component
I can set it to 0 again but 0.5 should make so it'll be centered
Not sure what you mean
Show your TMPro inspector
Oh my god I'm stupid lmao
Good point, just adjust where the text is alligned to
I don't know how I didn't think of that
@slow crag Here is a very broad example on how to properly implement asynchronous initialization. You should probably abstract most of this since it's a lot of repeatable code. https://hastebin.com/share/oxuyujumur.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I suppose I was still just confused by using the box collider which is set and centered differently than the rectransform
Notice how this actually properly handles any exceptions that might happen
So I didn't think of the solution of just centering the text within the field
Now just to figure out how I center it in code
center what in code now? The text or what is not centered, I am confused ๐
Basically pressing the second button but in code which centers the text in the middle of the bounding box :p
I just need to look up what the syntax is for it
your component already centers it, doesnt it? You just have to replace the text? Or do you want to create the TMPro Component on the fly?
It already does the latter
And it also doesn't use a prefab so I need to know how to set it in code lel
That should be doing what you want
Probably, but at this point I'd have to rewrite the code then for it heh
You're much better at googling then I'm lmao
Its just experience in googling for all those things the last years and years ๐
Fair enough hah
I'm still studying so I've not gotten all too much experience with Unity just yet
I've like 1.5 years of Unity and 2 years of C# I think
(My math is crap so if the numbers aren't right I blame it on that heh)
it depends on your learning resources too. Back then when Unity came out, you had to figure out everything yourself ๐ that helped a lot and still does to some parts of Unity where they just dont find time to write docs ๐ So you only had little amount of tutorials if at all, but today, its the way around, you just have too much resources on too many versions ๐ But enough off topic from me ๐
Well I try to do stuff on my own mostly, I think that helps learning more than just copying tutorials 1:1, hence I came to the solution of IPointer and then got blasted for using it and was said to use IDrag instead ๐
, it's still not really wasted time though, I learned from it :D
And it's just more fun designing your own things :p
Everything appears to be working fine now though, thank you so much!
Is there any way, I can check if my unitywebrequest code works without using an API to get data from
Why would I want to check every frame if it's initialized?
that's the exact thing I'm trying to avoid
keep Update as clean as possible
It's still unnecessary
Not really
Its just good habits to keep it clean
Again, not really
You're going to get a heart attack if you look at what Unity does in a single frame, if you think this is bad
This aint 2005, c# can check a boolean each frame
Point is, this is a quick and efficient way to ensure your code is initialized asynchronously, whilst also handling any errors
Don't use it if you don't want to ๐
True
The only concern you should have is heavy computing, recurring bigger tasks, or blocking tasks in general, on a main thread.
I agree with Sampai and Caleidon, keeping it clean is good as well as avoiding update if its unnecessary. Just getting a habit of when to use what can have impacts when you are in a bigger scope later.
I completely understand what you're saying and why, this is just a thing of opinion
I don't like my update calling if statements every single frame if I can avoid it with 2 lines of code
Alrighty, just remember that not handling errors from an asynchronous method like you're doing currently is a bad thing
I'm specifically avoiding that basically
That's true, but my method is designed not to have errors. If they do exist I'll catch them during development. Once the game is complete, it can either work 100% or not run at all, and if the latter is the case then that's on me
But either way, thank you for showing me an alternate way
I'll keep it in mind, might come useful later
My methods are designed not to have errors too
Yet they still happen
Sorry, does anyone have any idea on this?
Thinking your methods are perfect and will never give you any errors is a very very bad way of programming, especially with a fire and forget method you just introduced @slow crag
I strongly suggest you add some way to ensure it works. Atleast add a try-catch block into it
but this is resource loading
sure, a basic try catch might suffice
either the game loads the resources or it's like "fuck off I can't start"
Idk, seems to do a lot more than just that will all the extra methods it's invoking
But alrighty
Sprite swap?
You reference the script you need and create there properties or methods to access the data.
You can find tutorials pinned in #๐ปโcode-beginner to help you with learning C#/Unity basics how to do that
Im not sure that would work since none of this will be at runtime. I have getter that allows me to grab the list from the main script. But how do I display that in the inspector so that you can choose one value out of the rest?
[SerializeField] private ItemData newItem; // Needs to be one of the values from itemData.
private List<ItemData> itemData = ItemManager.instance.GetItemData;
private void Awake()
{
itemManager = ItemManager.instance;
}```
OnValidate triggers on value change.
You need to let your script run in editmode and then use some custom editor to created a dropdown based on your other script
So if its just for the displaying of it, look into custom editor scripting
okay I assumed it might come to that. Ill see if i can find anything. thanks
Is it possible to make ExecuteInEditMode only update when a value in the inspector has been altered? rather than whenever something in the scene is changed?
that whats Fogsight said, use OnValidate then
Also, !cs
haha my bad
Also, I cant seem to find it, but does OnValidate only update when the scripts object is updated? Or are all scripts with this function called?
When you edit something in the inspector
when any update happens in the inspector.
The function gets called
This works for inside of playmode and outside of playmode iirc
okay thanks
I have decided after remembering that scriptable objects exists that it is a much better option than defining objects in another script through the inspector.
thanks for all your help though!
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
OOOOOOH THANKS!
pls help me i want code where simulation is space moving object when click move forward go forward infinite and when rotate object and click move forward reduce speed and than go forward
crossposting wont make you get no help at all
hello. I need to know how to find out memory usage in while the user play, but not in profiler, but via script
Same to you, stop crossposting on all code channels please
Alright, but I just crossed post because someone tell me to ask me on another channel
what can i do? they didnt help me
Wait! patience is something you gotta learn to get help
Try to give as many detail about your problem as well as the code you have tried
Your question is very vague, not to mention it's not a question. We're also not here to spoonfeed you code. We can look at code you wrote that attempts to do whatever you ask here, but we're not going to straight up write it for you
If you're confused on how to do this, and want to learn how, #๐ปโcode-beginner has tutorials in the pinned comments to help you with Unity
You probably didn't get any replies because your question makes little sense, and lacks punctuation to make it readable
How can I get the forward velocity of a Rigidbody?
Hello
public class RotateBlue : MonoBehaviour
{
public GameObject Anchor;
public float speed;
public Vector3 Axis = new Vector3(0, 0, 1);
public bool onTile = false;
public bool hasclicked = false;
public Vector3 TileLocation;
public RotateRed red;
public bool isActive = false;
public bool hasswapped = false;
// Start is called before the first frame update
void Start()
{
onTile = false;
hasclicked = false;
isActive = true;
}
// Update is called once per frame
void Update()
{
if (onTile == true && isActive == true && hasswapped == false)
{
if (Input.GetMouseButtonDown(0))
{
hasswapped = true;
Swap();
}
}
if (isActive == true && hasclicked == false)
{
transform.RotateAround(Anchor.transform.localPosition, Axis, Time.deltaTime * speed);
}
if (hasswapped == false)
{
hasclicked = false;
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("tile"))
{
onTile = true;
TileLocation = collision.transform.localPosition;
TileLocation.z = -1;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
onTile = false;
//collision.gameObject.tag = "Untagged";
}
public void Swap()
{
hasclicked = true; //stops from moving
isActive = false;
this.transform.position = TileLocation;
//move oposite colour
red.isActive = true;
red.hasswapped = false;
}
}
My script is running fine, but the blue version of it is the same.
When they swap it straight away swaps back as it satisfies the conditions for some reason
how would i fix this
!cs
all it needs to do is swap over player, and its swapping over, except i cant click to swap as it straight away swaps back and displays like nothing hapopened
hi, do i have to learn c# first or just go for unity?
you can learn the basics by just starting using unity and following tutorials. Unity has official tutorial scenes
wont work lol
Yes it does
Wow what a bad example
yes it does value int void
ah done it now, i did a space b4 the cs
just removed hasswapped bool as that was just to test, isActive will be the main one
Yes this do ;0
it all works, ahh
It runs this code, but then it displays as it doesnt, as the other script makes these variables true/false
The this is unnecessary btw
yep i know. I added it incase it was messing up because of it. I need to remove it
Well you don't need to, it's just redundant
just realised. this.transform.position = TileLocation; runs. Nothing else runs!! but then it could be running, and it could just be switching back to true/false from the other script, but the other script shouldnt be running this since it shouldnt and doesnt detect the click since its deactive, unless because theres no delay, it is detecting the click in the split second when it comes back as true... ahh
cause it only does the click if its active, which until the code in Swap(); runs in the oposite script, it shouldnt be active, and isnt active
id send a video to help explain, but no discord nitro
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
!cs
video showing what i mean
You don't need nitro for that
mp4 would be nicer so it actually embeds
im spamming click which runs the swap method, but as you see in the inspector, it doesnt change any of the bool values
1 min
done, i spam to run the method alot
you can see it working, but the boolean values aint changing. I assume the oposite script is just changing it right back @woeful leaf
What exactly is the intended behaviour and what is it doing that is not the intended behaviour
it should change isActive to false, and hasclicked to true to stop it moving. It should then make the blue circle hasclicked false, and isActive to false.
but i assume when it does this, it straight away runs this on the other script, which changes it straight back
You don't need == true btw
just makes it easier for me to understand it ig
I mean fair Ig
Normally it's just used without it, and if you want to check for false you use !
But this only does it for the blue ball right
Where is the code for the red ball
it does it for both i think, let me check
it is doing this
just debug logged it
You have the same script on both objects or?
they are copies of the same script with red/blue values switched around
just these type of things switched
That's terrible
first, that ๐ and cany ou show your full script
You should look into inheritance or just use a main script that controls both
Both, please
In a pastebin probably
tried doing that, but had the exact same issue actually
Also you can just use public values on your different balls if needed to set the colors you want...
show your full script please
(!code)
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
This is probably not needed unless you do some very funky stuff that you shouldn't be doing in the first place
But yeah the problem lies in that you call both functions because they don't really know anything of eachother
It's poorly designed code
it makes one of them on a tile automatically. This means the blue circle will move defaultly
The booleans are false by default though
So why'd you have to do it again in Start
not sure
lol, just changed that
I think using a main controller script would be better in this case
What was the issue again? sorry, cant find teh original post ๐
You could use inheritance but I don't think that's the best option here
The Swap() method is being called simultanously probably
when it runs Swap() it straight away satisfies the conditions in the other player and swaps back over
But they are not related to each other, are they?
The problem probably lies in that the scripts don't really know eachother
tried that, but it got confusing to decide which one is active. lol... it ended up in several bugs and i couldnt get it to work properly
Oh wait, they are? you referenced them, okay, now I got your code
start by blue on default and then swap it around
What do want them to do?
Or red on default, it doesn't matter
Like if one swaps, the other swaps too?
they spin around eachother and if you click the one that spins snaps to a tile and the other starts spinning
^
nah, if red clicks on a tile, it swaps. It should then do the same with the blue, but it straight away swaps since it thinks you clicked on it as the swap over happens in a split second meaning the click is active on the blue and runs swap..
yes this shows it
is the game design going to only have two of those circles?
yes
If not then that's a whole other can of worms
Then it should just be a bool swapping state
yep
It should not be the hardest to implement
but thats kinda what ive done
But you went a very weird way with it
so you could just make a static bool which is redActive for example. so you know, what is currently the state
Or a main controller
BUT you have to use the same script if static boolean being used
or a main controller, yeah.
I think the latter would be the best
I don't see much use in having it the way he has now
And if he does want it that way he does have to use inheritence
Why? Blue and red are doing the same thing, just opposite
so you would say remove the active, and the swap function to be in a main controller script that changes the active seperately..
Yeah so a main controller would probably be better
Else it's just dupe code ish
@woeful leaf ?
Yeah you've like one script that's just on an empty gameobject that has a reference to the red and blue ball and controls it from there
At least I think that'd be a good approach
yep ill try that now!
I was assuming this to be a prototype. But I agree, if its a game he keeps on working, a controller is better to handle other states later
shouldnt be too hard to fix it
Even for a prototype, it's just harder to implement the way he's doing it right now
And just more inconvenient because he'd have to change both scripts if he wants to add something because he also doesn't use inheritance
Which in turn gives more dupe code
Thats why I said, do not use two scripts, use one with a static bool. that would be the fastest way for prototype, but if no prototype, more power to your maincontroller
Ah yeah I suppose you could just use one script but still slap it on both
But I agree, just add one more ball/circle, and that approach is gone ๐
Though I still feel like that'd become a problem at some point because you don't know which object you're using and else you've to define only do A if it is object B on a script that is on both object A and B
something like this?
Oh definitely, everything changes if you want to do it dynamically in that way
And it'll also be quite a lot more to manage
redactive = !redactive; and blueactive = !blueactive
thats what swapping "should" be doing
what?
It inverses the bools
Hey all, I have a question. If i have the red X as a position, how do i get the green X thats always the opposite side of the middle?
Math
or parent rotation with offset localposition
And you'd have to prevent the switching if the tile isn't hit
Out of curiosity, what's the code now?
ill send a video of what it was actually meant to be like lol
(As mp4 please)
also, you can just type blueactive = blue.isActive;
Why is this necessary
ohh i seee
if i add #if unity_editor at the start of the method and #endif at the end of the method, that means they will not be added to build right?
blueactive should be blueActive btw, code conventions
Yeah it'll only compile in the unity editor
Though the syntax is wrong, it should be in all caps
wrong way round ahaha
@woeful leaf
its terrible rn
but it works
the hit detection needs to be redone
plus i need to readd my code that means you cant go back a tile (just gonna untag the tile you exit as Untagged)
I don't get why you need this whole Update stuff
Can't you just activate the other in the Swap
oh yeah
LOL
im such an idiot
Have you done tutorials and stuff for C#/Unity? Stuff like Unity Learn !learn
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
The pins of #๐ปโcode-beginner also have stuff
i have indeed. Just my mind today
pretty much what i had b4 plus the main controller. Then instead of all the commented out stuff, just main.OnSwap()
Wait why do you still need a seperate script on the balls
Yeah because you still have scripts everywhere apparently
i got 3 scripts
main controller
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Use that one
It allows for multiple scripts
a powerful website for storing and sharing text and code snippets. completely free and open source.
By the way, why is everything public
so i could see when the boolean values change in the inspector. I would obviously make them private afterwards
You can use debug mode for that
i know.. idk why i did that
i wrote this up when i was tired last night, then came back to it this morning and was like ahh what have i done, and rewrote half of it lol
and just left them ig
Explains why the code is so questionable lmao
yep
Word of advise, don't write code when you're sleep deprived heh
yep
General rule: avoid public field like the plague, even when tired ๐
lol that would be a good rule..
Default everything to private if you end up needing it in another script you can always change it to public, if you only need it in the inspector, use [SerializeField] private
yep.
now how would i fix this main issue
By yeeting a lot of code
alrighty
I think a decent way to do it is have a script that delegates the OnTriggerEnter/Exits to the main controller script
For the rest you shouldn't need other code on the ball specifically
It's kind of hard for me to give a solution without completely writing it myself
yeah
ok
Which I'd want to, but I don't really have the time for it right now
And you should be able to use the same script for invoking those events, since one always stays still on a tile thus won't have OnEnter/Exit calls
hi, i instantiate prefab first and override it top prefab
if i call the method again i destroyimmediate them but they dont beacause they are overriden
i thought this would work but didnt happen
{
PrefabUtility.RevertAddedGameObject(missionElement.gameObject, InteractionMode.AutomatedAction);
DestroyImmediate(missionElement.gameObject, true);
}```
any idea how to revert override of nested prefab
public class TriggerDelegation : MonoBehaviour
{
public static Action<bool> OnTrigger;
private const string tile = nameof(tile);
private void Trigger(Collider2D collision, bool trigger)
{
if (!collision.gameObject.CompareTag(tile)) return;
OnTrigger?.Invoke(trigger);
}
private void OnTriggerEnter2D(Collider2D collision) => Trigger(collision, true);
private void OnTriggerExit2D(Collider2D collision) => Trigger(collision, false);
}
@terse venture probably something like that
The naming is a bit questionable in some parts but you can rename things yourself
i see..
thanks for the help!
And in your controller class you'd subscribe your function to OnTrigger
ill have a go at remaking this system
what does OnTrigger?.Invoke(trigger); do?
the rest i understand
oh i see
public class SwapController : MonoBehaviour
{
private void TileCheck(bool trigger)
{
if (!trigger) return; //Only continue with the function if a tile has been entered, not exited.
//Set the position of the coherent ball to the tile here
}
private void OnEnable()
{
TriggerDelegation.OnTrigger += TileCheck;
}
private void OnDisable()
{
TriggerDelegation.OnTrigger -= TileCheck;
}
}
Whenever a ball enters or exits a tile, tagged with tile, it will run TileCheck
i see.
This video explains how to use special delegates called Events in order to subscribe methods (functions) to create flexible broadcast systems in your code!
Learn more: https://on.unity.com/3iVYXhx
That might be a good video to understand events a bit more
thanks, ill give that a watch. Thanks for all the help today!
If I have the time, I'll try to write my own fully functional script of your problem, but I cannot promise I'll
yeah no problem! Thanks again
But the TL;DR is that your basically have to rework the entire system, right now it's just unstable with how many random and redundant things there are, making it very hard to debug
And just have 1 main controller script (On an empty game object, make sure there's only 1 of it) and 1 delegation script for the OnTriggers (Which'll be on both balls)
Else you could go for Inheritance, but I think a main controller would be better
I'm making a movement based game where i set the rigid body velocity every frame (fixed update). i only need rigid body for collision detection (so that i dont go through walls). I would like to get rid of rigid bodies completely if possible, including collision detection in my velocity script. is that a good idea?
You cannot have collision calls without a Rigidbody
And if you directly use the transform, collision calls can be buggy
How would one get the input for the right joystick? I'm not switching to the new input system it literally snaps to directions instead of being free and nobody knew why. Its really tedious too
How do you expect to move using velocity if you don't want to use rigidbody and collision detection?
modifying the transform position
As I said, that's not the best idea
If you don't want to use the physics engine, you can move by manipulating the transform, but you need to create your own collision system . . .
If it's a simple game AABB collision will get you relatively far
create an axis for your joystick and use that.
But that'd still be a pain to set up
Thanks my bad
yes that's what i'm asking about. game's physics are arcade style and not realistic
https://answers.unity.com/questions/1350081/xbox-one-controller-mapping-solved.html Maybe this helps
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
You can make the game's physics quite realistic if you want to
I'd advise against writing your own physics for everything
Unless you've a lot of time on your hands and want to die due to math that is
Definitely if you want to have it realistic
again i dont need it realistic. for one of the abilities i'm using a collider that's just raycasts in for cycle. (unity physics collider didnt work quite well)\
Then this is poorly worded since you said they're already not realistic
So what's the problem
Why do you want to get rid of rigidbodies?
This doesn't make sense. Collision just stops objects from colliding when they intersect. It has nothing to do with making anything realistic . . .
You don't have to use everything
Collision detection is the physics engine
raycasts and colliders are also the physics engine
seems like you're using quite a lot of it
^
Either you use the RB or you write your own physics
If you like torture, go with the latter
okay i got you
hey, so maybe im looking in wrong places but i honestly cant find a proper solution, so basically i have a bird gameobject, and a wing gameobject as its child. i basically just want for wing animation to play when i press space and for the bird animation to play when the bool is set to true. i have a seperate script with settriggers etc. so basically now what do i put where, because putting animator and animatorscript components to both of them separately simply breaks the whole bird
i would really apprecieate any tips
It's really an #๐โanimation question, try asking there
alright i will, thanks
they arent just buggy, they dont work ๐
Yeah that's what I meant but it's been a while since I encountered the problem since I don't combine the two so just to be safe I called it "buggy"
It not working is still buggy ;)
yes yes
@woeful leaf I found your way a little complicated, but when messing around with my previous script i somehow got it working!!
Nice!
Yeah events are a doozy to wrap your head around, but they're very useful
How did you fix it? ๐
i made it so if the ball isnt moving its counted as its no longer on the tile (even if its sitting on the tile). This means its only checking for whether its active (for movement), and im moving it via the main controller script
Im now encountering a problem with my game. I know a fix, but im not sure how id code it
What is the problem?
on these corners, it overlaps the 2nd tile infront, meaning you can jump 2 ahead
So my thought was getting all of the tiles in an array, and every time you jump a tile, it gets the next tile in the array and changes the tag to tile
Keep an index of every tile, if the index is 2 ahead instead of one, don't allow it to snap to it
Yeah pretty much
but
how do i get the tiles in an array. Ive only had to use GetComponentsInChildren, and done it like that, but im not getting a component
you cant do getchildren
Show your hierarchy
i havent put them into an empty gameobject yet
Yeah you need a parent with a script on it
GetChild is a funciton on Transform, not GameObject
yeah, i figured that
so ive now got all of the tiles under a parent gameobject
GetComponentsInChildren is not going to give you them in any particular order
so i could take the transforms and get the gameobject and tag them with tile, but now i gotta do that 1 by 1 and not in a foreach loop right
loops do it one by one
not sure why would want to not use a loop
How would I rotate it by x degrees around the x-axis?
yes, but how would i make it so it would only do it like
if(tile.hasmoved)
nexttile.tag = "tile"
myTransform.rotation *= Quaternion.Euler(x, 0, 0);```
*=?
what does hasmoved mean?
yessir
i have a context menu method, which do fill a list by parent. but when i call it via context menu prefab doesnt get overriden, so i have to create a gameobject then override the prefab, is there anyway to save it without creating gameobject
Okay. Thank you ๐
it's a short way of writing this:
myTransform.rotation = myTransform.rotation * Quaternion.Euler(x, 0, 0);
well ill add it somewhere here. so when you click, it gets the next tile and changes the tag ect
Yeah, I know. It just seemed weird to multiply. I am guessing it has to do with Quaternion math (which I know nothing about)
yes when you use the * operator with quaternions it "composes" them
think of it like adding rotations
That's so cool
so here we start with the object's current rotation and "compose" the additional x axis rotation afterwards
localVel = (transform.forward * Vector3.Dot(transform.forward, rb.velocity));```
I have this vector for forward/backward velocity. I can use the magnitude to figure out the speed, but how can I know if I am moving forward or backwards?
how would i make it so when i press a key it would go through the array setting the tag for each gameobject
Are you using the new or the old input system?
If you are using the old one this should work:
if (Input.GetKey(KeyCode.T)) // Tag
{
for (int i = 0; i < array.length; i++)
{
array[i].gameObject.tag = "tag";
}
}
I'd do it this way:
Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity);
bool isForward = localVelocity.z >= 0;```
foreach (Transform child in tileparent) {
child.tag = "whatever";
}```
Interesting
dot product would also work yes, the dot product would be positive for locally forward velocities and negative for backwards
so actually our two techniques I believe will give the same Vector3
Wait now I'm confused
so you could also check the sign of the z value of your localVel in your example
and that would work too
So the z component is the "speed"?
no
z component is the z component of the velocity in local space
it's the speed on the local z axis only
ignoring x and y
Why do I want to use the z?
because the Z axis is the "forward/backward" axis
whereas y is up/down and x is left/right
and you wanted to know if you were going forward or backward
So the forward/backward speed is the z value?
yes
z is part of the direction of your vector, speed would be the length of your vector in that direction if you will. Not sure if this clears things up or not ๐
thanks!
thanks! you both have helped!
Any idea why web request downloadProgress would remain at 0? It jumps to 100 when it's done. It's about 1 min to download so it's not that it's going too fast.
webRequest.downloadHandler = new DownloadHandlerFile(tempZipPath);
webRequest.SendWebRequest();
while(!webRequest.isDone) {
OnDownloadProgress?.Invoke(fileNumber, fileTotal, webRequest.downloadProgress,version);
await Task.Delay(150);
}
From the docs:
Note: This property only works if the serverโs response contains a Content-Length header and the UnityWebRequest has a DownloadHandler attached to the downloadHandler property.
yeah, your app does not know your size you gonna get if the servers not gonna tell
does the response contain a content-length header?
You can check by doing the request in a web browser with developer tools open
and checking headers
That could be it, it's a chunked transfer as well so that might make content-length a bit weird to figure out
Just open it up in your browser and check Network => Headers ๐
This here should be there:
So you can calculate either with downloadProgress or you calculate it with bytes loaded vs that value
does anyone have a playermovement script that would be good ?
similar to clustertruck...
Ah yes let me just write up a movement script for you
We don't just hand you code, you come with a problem and have tried and attempted solutions and then we'll eleborate on that
this annoyingly is just making all of the tags "tile" straight away
why would that be
i also tried doing
tile[value].gameobject.tag = "tile"
and then adding to the value
cause you set all tiles in that array to be tile?
If it's a prefab you can just set it to tile by default
And every tile will be labeled with it
Is GetComponent cheaper then TryGetcomponent
I really canโt profile these tiny functions
It really shouldn't matter much if any
Its just a bool you can use instead of just running into null errors
If the difference is so small that you can't even measure it then it doesn't really matter, does it?
im trying to do this
all of the tiles are tagged "next tile"
if the tile is the next tile
tag it "tile"
so i was gonna do this: If click and land on previouis tile
add a value to the tile array
set it to "tile" so next tile is tile
or you can jump 2 tiles on corners
What exactly are you trying to achieve with your tile tagging? Is it checking against tile to be able to drop your circle?
Something seems to be wrong. The z-value is only right if I am moving along the world z-axis
can you show your code?
this shows a clip of the game. I stopped at the corner, but you can see how you could skip the corner tile. So i need to make ONLY the next tile to be tagged "tile"
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Imagine someone with mobile screen trying to read your screenshot ๐
And what is happening right now, what is not working?
can you try this:
Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity);
bool isForward = localVelocity.z >= 0;
Debug.DrawRay(rb.position, rb.velocity, isForward ? Color.green : Color.red);```
It seems like you're trying to draw local velocity in world space which doesn't make much sense haha
You probably want something like
tiles[currentIndex + 1].gameobject.tag = "tile"
where currentIndex is the index of the current tile
as soon as the method starts, all of the tiles go to "tile" instead of "nexttile"
public void OnTile()
{
for (int i = 0; i < tile.Length; i++)
{
tile[i].gameObject.tag = "tile";
}
}
yes!
yeah, because you set them too. Where is tile array coming from?
the for loop you have above will run for every single tile in your array and set them all to "tile"
oh ahaha
basically it breaks down to
tile[0].tag = "tile"
tile[1].tag = "tile"
etc
you can use tile.IndexOf(this) +1 for example to get the next tile.
i see..
not sure indexof is working with an array, but you can just use a List instead
ill try this though
You'll just need to keep track of currentIndex yourself
That is going to cause an exception
be sure to check that currentIndex +1 is not out of bounds of your array for the last tile
Ayy! That seems to work
Thank you ๐
the starting 2 tiles are already tagged as "tile". (i need them to be). So to fix the rest , i assume i should make the index -2 on start?
wait 2
try with 2 to start, try 1 if that doesn't work
depends if you're current tile needs to be the second square there (index 1) or the third that's a bit off screen (index 2)
weird, the 3rd tile gets tagged as "tile" when you land on the 2nd tile. Which is correct. Then when you land on the third tile, it does nothing to the 4th tile ect
@vast matrix
what gets called when you "land"?
tile.OnTile();
public void OnTile()
{
tile[currentIndex + 1].gameObject.tag = "tile";
}
which does that
and where do you set currentIndex?
public int currentIndex = 1;
and where do you update it
in this script
thats not updating it
thats just always getting currentTile(2) every time OnTile is called
i thought
tile[currentIndex + 1].gameObject.tag = "tile";
updates it by getting the currentIndex and +1 to it
theres no assignment here
tile[currentIndex++] will also work
that will work for ONE more tile now ๐
if you want to increment after the calculation
or do you set it from a main manager?
oh ok
Oh my bad, I think you have amain manager class now.
++ is currentTile += 1
Can you tell me if I have a struct called "Tile", and I make an array of Tiles, those are all data types. But if I make a list somewhere else and add them to the list as well, are they copied as a data type or a reference?? I seem to remember something about list entries being references but not sure.
yep
If they it's a struct, they are copied by value
not reference
if they it's a class, they are copied by reference
whether its placed before or after the variable dictates when it is incremented.
++currentTile will use currentTile += 1 *before the assignment, so it'll run the next tile. and increment.
currentTIle++ will do the logic on currentTile then increment by 1.
structs are value types. they are copied, not referenced . . .
perhaps I'm not good at explaining
and I can't reference the structs other than unsafe code and pointers then?
hm its not working ๐ค
What means not working?
testing it again rn
1 sec
it didnt tag the next one
i messed around with the starting number too
You can get a reference to them, but only within the current scope. You can't store references to them without unsafe pointers.
read this @terse venture
your script is in a manager class right, can you show your full function that gets called?
Well you can use ref out in keywords to pass it by reference into methods, but otherwise, no
alright thanks
You could use an array index to reference one if it's in an array
i see.. ill try them both
ah doing ++currentTile worked!
thanks alot guys!
i did get this error when it was on the last tile
yeah, we said that ๐
(since next number is out of the array) like you said
check if currentIndex+1 is smaller than your array length
do i just check whether the current index is smaller than the length
ah yes
cool
place a check to make sure the index is not out of range . . .
if(currentTile >= myArray.Length) return;
//logic


