#archived-code-general
1 messages · Page 88 of 1
Post full current code please. You're just trying to get it to move in and out locally, right?
yes
Vector3 dest_position;
void UpdatePos()
{
float map = mapfloat(progress, 0, 1, 0, 0.016773f);
dest_position = Vector3.MoveTowards(transform.localPosition, new Vector3(start_pos.x, start_pos.y, start_pos.z + map), 1);
// transform.Translate(dest_position - transform.localPosition);
transform.localPosition = dest_position;
if (debug)
{
print(dest_position);
DrawHelperAtCenter(this.transform.forward, Color.blue, 0.5f);
}
}
that's the important code
this
dest_position = dest_position - transform.localPosition;
should be
dest_position = transform.localPosition - dest_position;
still shoots out to infinity
because you want to move the difference between where it is now and where you want it to be
and that
kinda works but
What is mapfloat
float mapfloat(float value, float from1, float to1, float from2, float to2)
{
return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
}
this function maps a float
it works as expected and returns correct values
Ok lemme write something up
okay
I'm on a phone so give me a bit
are you reseting start_pos every frame?
wow coding on a phone
no
Yah not ideal lol
void Start()
{
start_pos = this.transform.localPosition;
if(debug) print(this.name+" : "+start_pos);
}
then your code is totally illogical
What is progress? How does that get set
var targetPos = start_pos + Vector.forward * progress * 0.016773f;
transform.localPosition = Vector3.MoveTowards( transform.localPosition, targetPos, 1);
Should do
look at what your code is doing, you are always moving away from where you started so, of course, it will eventually reach infinity
Just make sure you're never resetting start_pos
it's still in the Start() function so sure
wait why Vector3.forward
oh
nvm
Bc you're in local space
ohh
i forgot about that
still moving in the wrong direction
ah man I thought that was it
Define wrong direction
you see that blue line coming out of the z arrow?
it should be moving in that direction
and int moved up on x
local
you can see that here
and I have no idea why that first one moved correctly
I think it is time to check your assumptions. That code should work
What happens when you rotate the parent. Does it always move in the same global direction
Is your screw object split into a parent and child object, where the child has the graphics and parent has the logic?
Global direction?
local
Draw a ray for start_pos to target_pos
the bolt has Y rotation of 90
okay
Then also run transform direction on that ray and draw that too
It's drawing at origin
the blue ray is transform.forward
It's relative
to what
I'm just running you through the debug steps I would do
To start_pos and targetPos
DD:
Do you have local pivot turned on in the editor
yes
Where is it on the screw
Suspicious
What's the dotted line in blender
Screenshot of unity hierarchy of screw
it shows the object it's parented to
Ok
now I'm just wondering, why transform.Translate moves the bolt correctly
like on the local correct z axis
my god
i changed Vector3.forward to transform.forward
and it works
shit
now if I unparent something it breaks
Ok grab your bolt into a new scene
Or just put it at origin or something
Unparented
Ok now put it under an empty, un rotated parent at origin
Use Vector3.forward in these tests btw
Ah I think I got the issue.
Try this:
var localForward = transform.localRotation * Vector3.forward;
And use that instead of Vector3.forward
I'll try
so i have a piece of code that gets info from a google sheet but how do i set the value (I'm using CSV)
oh my
that
works
2 days of nonsense
constant suffering
for that small fix
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm a bit rusty and also on a phone, sorry for the roundabout debugging
But! This is a good example of what you can also do when debugging. Break it down to component parts and test everything in pieces
Being able to solve your own problems is a wonderful skill when programming
Just takes practice
Ciao
bye
if I have several components that all implement IExample, and I want to modify the transforms of all IExample objects, how can I add all of those objects to a list/array to apply transformations to them? I thought I could use FindObjectsOfType<IExample> but that method apparently can't take interface type parameters
is the solution to just, not use a collection at all?
is that even possible?
depending on where the components are, it might be better to do it another way. If its all children of an object for example there are different functions you can use
thanks, exactly what I needed
im pretty sure its not good performance, i just dont know much about your structure
probably fine for just getting something working though for the time being
Hey, I want to initialize an array, what am i doing wrong?
public SetAndOpenMenuButton characterButton;
public SetAndOpenMenuButton inputFightButton;
public SetAndOpenMenuButton inputExploMenuButton;
public SetAndOpenMenuButton logButton;
public SetAndOpenMenuButton spellExploButton;
public SetAndOpenMenuButton[] setAndOpenMenuButtons = new SetAndOpenMenuButton[6] { settingsButton, characterButton, inputFightButton, inputExploMenuButton, logButton, spellExploButton };```
whats your error?
can you show the actual error, im not a computer i dont know the codes
A field initializer cannot reference the non-static field, method, or property 'name'.
name being each of the SetAndOpenMenuButton
when you googled that error, did you come across this link (which i assume your text is taken from)
https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0236
your variables arent initialized
the example in the link shows you how to do it properly
Cos I define them in editor?
they still have to be in a method body
the editor is not related, you shouldnt assign these things outside of a function
I thought my problem was the initilization syntax
Okok ty
So I understand it's not strictly programming, but can I ask a math/physics question here? I promise 100% it's related to programming lol
no
if it's general programming , not unity that is
just ask
I'm making a small tower defense game where we have to use the kinematic formulas for calculating the projectile's movement. My team decided it would be cool if you could aim the projectile with the mouse cursor, so I found a good tutorial and adapted it to what we want. It works really well, but one of the requirements is that the player is able to set both the initial velocity and the angle. Is it possible for the player to set the initial velocity and angle when it is already known where the projectile is going to fall because of the aiming?
As I have it right now, the initial velocity needed to get to the point with the given angle is calculated for you. I haven't taken physics in ages and I've never been very good at them so I'm sorry if its a dumb question I'm just struggling a lot with this
I'm getting a null reference error that I can't find an explanation for. I'm not sure what change I made that caused this. I press play and I get an NRE directing me to a line in my PlayerController where I set an animator parameter. This suggests that playerAnim, the Animator component on the player, is null. But the player definitely has an Animator component as shown here. Furthermore, my attempt to verify in-code whether retrieving the Animator was successful isn't working, I added this debug statement, in the PlayerController's Start method, but it doesn't appear in my logs. Sorry for the image spam, just want to provide all the necessary context.
Worth noting: If i try to comment out the function that calls a method on the animator component, it finds another component to throw an NRE for, even though those other components definitely exist on the player as well.
log it immediately before you use it
you might have an extra copy of the component lying around
If you set the initial velocity and angle, you will land on a given point. (Given that the acceleration is set)
So no, you cannot set the displacement, velocity, angle and acceleration.
logging is really just not working the way it should at all
Thank you for confirming, that does make more sense. I was trying to figure out if there was any way that would be possible but it just didn't seem so.
I'm not sure what you are expecting to happens.
You should challenge your team and see what is the true issue.
Doesnt mean that the animation is never assigned ?
it is though, as evidenced by the odd debug statements
I mean, you might want to debug that.
well
do you have a suggestion?
I've found that the animator exists/is not null, but I'm getting an NRE immediately afterward when I call a method on it
Follow the function call and look why it is not reaching there ?
eh?
if it was making it into the function call at all, the stack trace would show that
oh no, it works perfecly as is right now. The player can set the desired angle and also aim with the cursor in a 3D terrain. We were just wondering if it's better to be able to set the initial velocity or to be able to aim the projectile, I guess. In my opinion, it's much more fun to be able to aim, so I think we'll just keep it that way. Thanks for the help
but the stack trace ends at this call, suggesting that this call is being made on a null reference
it seems pretty cut-and-dry
line 142: it does not equal null
line 143: null reference exception
I see now. It is just there like 5 images.
if you'd like, https://hastebin.com/share/ezujomisex.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not the cleanest though
yes
("Object exists?" + playerAnim) != null
operator precedence! addition beats comparison
and, since playerAnim is null, it becomes the empty string
Alright, confirmed that the animator does not exist
then GetComponent isn't working for some reason
that's much more sane
Make sure the animator is on the object you're querying
yeah it is
is this the right object, though?
That doesn't mean that's the object you're querying
sure, let's log it real quick
is the script attached to PlayerBody?
Does rpgCharEvents = GetComponent<RPGCharacterAnimatorEvents>(); exists ? Otherwise playerAnim = GetComponent<Animator>(); will never be called.
Oh, also you probably have multiple scripts in your scene running at the same time
So make sure you only have one playerbody
good point let's take a look
i think you're onto something, because that log statement in my start method isn't showing up
Ookay, yeah I see now, there's a much earlier NRE that only happens once, but as @steady moat figured out, it stops any further components from being retrieved. Thanks!
now to try and recall what i was doing before this mess
Yah good tip when addressing errors: start at the top and work down
Im unsure how I can implement additional logic for my character when some parts depend on it being a player or AI.
Character script, this is on a character. It takes character settings
https://paste.ofcode.org/3bwnccH7PMEm48CJWdDgdew
The character settings:
https://paste.ofcode.org/3aL62qJDaGXCCEhH9RRJSEy
Example input manager for the player
https://paste.ofcode.org/ETVf25aHXnVjTAeGyH28W2
I have the script CharacterMovement which applies these movements from Character. i cut out most code because the logic is not the issue.
https://paste.ofcode.org/c842JzcpqhDmPHWRUNecb9
My player moves in the direction of the camera, so i need a camera transform stored somewhere
The AI im making will walk to the player if the player is in range (or in a box collider)
With this design principle, how can I include a unique behavior in this script such as rotation, since the rotation depends on if the character is AI or player?
Should the camera/player reference be included in the characterSettings data and then ICharacterInput include a rotation method? What about the box collider on the AI
Most of the code is really small just because again the logic is not the issue, i have another test script where I do the player rotation properly. Its a matter of how should I get this working with a script that moves any character?
You have the right idea separating out the input from the character controller. Store the camera info inside the player input and calculate camera relative input there, that gets passed to the generic character controller as pure worldspace input direction info. The AI player will pass world space input always
Basically, you're creating a translation scheme between specific control and generic control. Anything that is needed for generic control lives in the generic controller, and everything that's needed for specific control lives in specific controller, and the specific controller translates all of the specific control into variables the generic control understands.
For another example, if you wanted to add look direction to your controller, then look direction would be calculated by the camera in player controller, and the AI in the ai controller, and then passed to the generic controller as "look direction". The generic controller doesn't care how it gets calculated.
I see, i guess the issue im facing was that the input manager for player or AI isnt directly on the character, so i cant just drag in the objects I need like camera transform or player transform
By look direction I meant a visual head turning behaviour, btw. Realized that was unclear
oh yea i understood
So there's a couple ways to handle this
One is to make your player input and everything a monobehaviour component
hm if its monobehaviour I can attach it to the player and then still insert that specific instance into character instead of a new ControllerInput() right?
that really does sound easiest if it works, since i can get component by script
Correct, though it escapes me whether you can serialize abstract references in the inspector.
I think you can, but you'll have to try it out for me
If you want to drag it in the inspector that is
yea i will, thanks a lot for helping
Script assignments will work fine
I'm using the UniTask package (which works almost just like normal async await, but it respects timescale) and I'm hung up on a new issue. I'm gonna use a screenshot to describe the problem cause it will be a lot easier to follow than a set of pastebin links.
Lines show how the methods are supposed to be called. For some reason it reaches 40| Debug.Log("fireasync"); in the middle, but then it just sits at 41| pattern.ShootPatternAsync(....) until I stop the game. There is no loop to get stuck in. Can anyone tell what's going wrong?
You can do this, assuming I understand what you mean.
To serialize abstract reference, one most use [SerializeReference]. Alternatively, before [SerializeReference], we would use hidden MonoBehaviour.
I was talking specifically about an abstract monobehaviour
What do you mean by hidden monobehaviour?
how many tasks are there? is it possible numSteps is 0? The only thing i can see is that maybe u need to return a completed task inside ShootPatternAsync but its been awhile since ive worked with this stuff
Hey guys, in a 2D game, how do you control how your sprite appear vs stuff in the Canvas?
I tried sorting layers, didn't do anything, I tried moving the hierarchy around, didn't do it, I tried moving the Z position, didn't do it.
In my canvas there's an image and this image will always be on top of anything outside of the canvas
I'm not sure how to check the number of tasks, but if I try to shoot the pattern 5 times, then I get 5 errors when I stop the game. There are two other implementations of the shot pattern that don't have any awaits in them, and they got compiler errors until I made them return completed unitasks. The one that does have awaits will error if I try to return a completed unitask in it. None of them work.
did you put the Canvas in ScreenSpace - Camera
sort order should work by then
If you're using a Screen Space - Overlay canvas, yes the canvas will appear on top of everything else.
If you make your canvas Screen Space - Camera, you can put things closer than the canvas plane distance and it will show in front of it
you could check the number of tasks just from the list, before you use WhenAll(tasks)
If you add a debug as the first line in ShootPatternAsync does that ever print?
One other issue could be if you are trying to await the same task twice
like if _fireables somehow has a duplicated entry
I dont know what else would cause this issue, the "return a completed task" suggestion assumed ShootPatternAsync actually runs but I see thats likely not happening
Thanks a bunch to you two, that indeed was the problem!
One possibility is you have an exception being thrown somewhere in your task(s)
o i cant believe i forgot to suggest that possibility, I even saw that on the UniTask docs
Does anyone know how I can go about manually selecting the device I want from my devices list in the new input system when I have multiplayer local coop? Can't find any documentation on it
But what device would you use to select the device 😮
Hey Team,
So I just had a first with Unity,
Windows 11 using 2021.3.8f1 & 2021.3.22
My build runs fine in the editor, but when I build and run for windows, it will go to the splash and then just crash.
Are there logs anywhere I can look into?
PlayerLogs or CrashFile
That was it.
Thank you!
I assume this is bad xD
Yeah there is literally a site name after it xD
When you're making an interactable object that uses UnityEngine.EventSystems interfaces (e.g. IDragHandler), how does it quantify what the selectable area is for the object? I've gathered it works off the renderer rather than any collider, but I'm still unclear on if it selects a specific collider or somehow aggregates all the children that have renderers.
Does this question make any sense?
goes by the boundaries iirc
like the gray boundary you see with rect tool
iirc it also includes the children rects
gotcha. Curious if there's a way to see that boundary in the inspector, for 3D objects rather than just UI elements
yes, like I said use the Rect Tool
oh right you edited it
cheers thanks
probably generates those rects using the renderer's bounds struct
hm I'll have to check the layers because I realised there was already a visible collider as a child of the script, that didn't seem to trigger the event
you have collider on UI element ?
im a bit confused
Why is scene management so confusing? I've figured out a way to transition from the start menu to the game. The SceneManagement.GetSceneByName() Is supposed to have a string argument, right?
So why does it not accept a string as the argument?
but it does?
Not for me.
Manager or Management?
Unless my code is wrong? SceneManager.LoadScene(SceneManager.GetSceneByName("MainLevel"));
(SceneManager.GetSceneByName("MainLevel")); is underlined in red.
what’s the error?
Argument 1: cannot convert from 'UnityEngine.SceneManagement.Scene' to 'string'.
I looked on that unity webpage Null loves sending to people, but it doesn't really help.
LoadScene takes either the scene’s index or scene’s name
it doesn’t take an actual Scene
How do I find the scene's index or name?
with your error, its telling that you that LoadScene was expecting a string but you provided it a UnityEngine.SceneManagement.Scene
LoadScene("Main Level"); or LoadScene(0) depending on its build index
you have its name in your function
Ah. OK.
you already have all the info 
Ah. That worked. thanks.
When looking at errors, make sure u try to understand what its really telling you as well. If its cannot convert X to Y, that means the type is Y and it wants Y somewhere but you gave X
if you're confused always look at !api
💻 Learn in detail about the scripting API that Unity provides https://docs.unity3d.com/ScriptReference/
don't know why, I didn't make the prefab but now I'm tasked with working on it
@potent sleet also it's a world space object
but the collider still doesn't seem to do anything
UI element should not have collider
do you have an Image component on this world space canvas ?
or is it spriterenderer
A couple of MeshRenderers. It still works but I was trying to make sure I understood exactly how, since I'll need to make some new code that edits the values in runtime.
I need to set up the renderers so they're invisible but still register the drag indicator
Nvm someone already answered
but become visible under certain circumstances
Could anyone point me into a direction to find how to implement mathematical formulas into code. Where would I learn how to practicality implement formulas into actual projects.
lookup the formula in google and add C# at the end of it
chances are someone has translated it
Hello. I am making an online card game using Netcode for Game Objects. Right now I am spawning the cards in the hand serverside, and I have logic for the player to drag-and-drop cards onto the table. However I am running into all sorts of error with desyncing networkobject or networkbehaviour states, I think because fundamentally I am moving cards client-side but not sending that serverside even though the server owns the cards. Right now I have an event that triggers when the player chooses to play the card, and that trigger is what causes the errors.
My question is, what is a good design or best practice for netcode for a card game? If I could look at example written in Netcode for Game Objects it would really help.
I have a HUD which displays the lives. I have one life in the editor and try to introduce new life UI elements when the following function is called (see screenshot)
public void SetAmountOfLives(int amountOfLives)
{
// ...
float objWidth = lifeRect.rect.width / 2;
for (int i = 0; i < amountOfLives; ++i)
{
GameObject obj = Instantiate(_LifeObj, _panelObj.transform);
RectTransform objRect = obj.GetComponent<RectTransform>();
objRect.position = lifeRect.position + new Vector3((-amountOfLives / 2 * objWidth) + i * objWidth + (amountOfLives % 2 == 0 ? objWidth / 2.0f : 0), 0, 0);
_lifeObjList.Add(obj);
}
//...
}
The issue is that at different resolutions, the space between the hearts changes for some reason. Any way to fix this?
Have you setup anchors for that element? If your Canvas is on a set resolution with a Canvas Scaler component, and your anchors for those elements are setup for the location and space on screen they should try to occupy, then the whole canvas should scale with resolution
Does that answer your question?
My artist did a lot of the UI
I am just the programmer trying to fix it
xD
That looks like its using default values, what is your "Health" container using? The docs may help for understanding anchors better as well: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIBasicLayout.html
Got an school assignment in C# and running into some issues if anyone wants to lend a hand.
Trying to do an if inside an if statement but for some reason it doesn't feel right aswell as does not work the way I'd like it to work..
Down at:
else
{
Console.WriteLine("\t Sorry, I do not understand what you mean.");
// Go back and ask if user wants to play again.
}
using System; // Small "s" character
using System.Net.Security;
namespace slumpat
{
class Program
{
static void Main(string[] args)
{
// Declatation of variables
Random rnd = new Random(); // Creates a random object
int gameNumber = rnd.Next(20); // Calls upon next method to create a random number between 1 and 20, added a limit of 20 numbers.
// läs på, vad är overload metoder? https://msdn.microsoft.com/en-us/library/system.random.next(v=vs.110).aspx
bool game = true; // Variable to control if the game shall continue
while (game) // removed !, we're already checking the game variable for a true statement above.
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out int input); // Avoiding crash upon wrong input.
// Try, catch version
/*
* int input = 0;
*
try
{
input = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("\tError, please. Input a number from 1-20!");
}
*/
// If, if and if is incorrect format. If, else if, else. Or change to switch using case 1-3.
// else if, + tal was missing an + in-order to continue the code.
if (input < gameNumber)
{
Console.WriteLine("\tThe input number " + input + " is too small. Please, try again.");
}
else if (input > gameNumber)
{
Console.WriteLine("\tThe input number " + input + " is too big. Please, try again.");
}
else if (input == gameNumber) // tal = --> tal ==, closing opening brackets we're missing.
{
Console.WriteLine("\tCongratulations, you guessed the right number!");
// Avoid closing program to showcase result.
Console.WriteLine("\tDo you want to play again? [1] Yes, [2] no.");
Int32.TryParse(Console.ReadLine(), out int nextGame);
if (nextGame == 1)
{
Console.WriteLine("\tAwesome!");
gameNumber = rnd.Next(20);
}
else if (nextGame == 2)
{
Console.WriteLine("\tThank you for this time!");
Console.ReadLine();
game = false;
}
else
{
Console.WriteLine("\t Sorry, I do not understand what you mean.");
// Go back and ask if user wants to play again.
}
}
else // added else
{
Console.WriteLine("\tSorry, I did not understand that.");
}
}
}
}
}
Why am I getting this error message "NullReferenceException: Object reference not set to an instance of an object", my script is working correctly.
[RequireComponent(typeof(AudioSource))]
public class BallAudioController : MonoBehaviour
{
[SerializeField] private AudioClip bounceClip;
[SerializeField][Range(0, 2)] private float minPitch = 0.8f;
[SerializeField][Range(0, 2)] private float maxPitch = 1.2f;
[SerializeField] private float minVelocityMagnitude = 0.5f;
[SerializeField] private float maxVelocityMagnitude = 5f;
[SerializeField][Range(0, 1)] private float minVolume = 0.2f;
[SerializeField][Range(0, 1)] private float maxVolume = 1f;
private AudioSource audioSource;
private Rigidbody ballRigidbody;
private void Start()
{
audioSource = GetComponent<AudioSource>();
ballRigidbody = GetComponent<Rigidbody>();
if (audioSource == null)
{
audioSource = gameObject.AddComponent<AudioSource>();
}
}
private void OnCollisionEnter(Collision collision)
{
float impactMagnitude = collision.relativeVelocity.magnitude;
float pitch = Remap(impactMagnitude, minVelocityMagnitude, maxVelocityMagnitude, minPitch, maxPitch);
float volume = Remap(impactMagnitude, minVelocityMagnitude, maxVelocityMagnitude, minVolume, maxVolume);
audioSource.pitch = pitch;
audioSource.PlayOneShot(bounceClip, volume);
}
private float Remap(float value, float from1, float to1, float from2, float to2)
{
return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
}
}```
can you mark line 34?
in your script
audioSource is likely to be a nullptr which means it isn't assigned
Your script likely stopped working at that point
if it still works, try to clear errors and check if it appears again. If it does, make sure you are looking at all instances of the script
Yeah, it's working but gives the error message. I have just one instance of the script in the game. Should the audiosource component have some sound assigned to it or something? I'm currently assigning the sounds directly in the script.
Audio clip is set to none, which is probably the source oif the issue
The Start() assigns it even if it's null by adding the component
If that text object that seems to be holding your hearts doesnt already, you could try adding a horizontal layout group, then it can control the spacing of each element for you, otherwise, I would maybe make a new empty rect transform and set its width to what you want it to be, then set its anchors to match, and make your heats a child of that object
Didn't help adding an audioclip there.
Adding horizontal layout to the parent of the hearts?
The collision event can fire before the start() fires potentially?
Impossible
Try making the audioSource variable public and assigning it in the inspector
Don't, use [SerializeField] instead of makign it public
how ParticleSystem counts particles when it has child systems?
For example if there a hierarchy and I want to modify all particles directly through GetParticles(array) SetParticles(array)
Do I need to go through each particle system or only root one?
Thanks! That solved it (though I used serializefield like wardergrip suggested)
Sounds like it was indeed firing the collision before the Start() had assigned/created it properly 
Okay, in hindsight, perhaps making the component is a delayed execution https://docs.unity3d.com/Manual/ExecutionOrder.html
To clarify, public allows any class to access that variable and do whatever they want with it (unsafe)
private makes that access only to your class, [SerializeField] allows you to change it in inspector
Yeah, to the parent of the hearts, the layout groups will reposition the child objects (and overwrite any position changes while its enabled)
any way to make it appear under the text?
Please ask in the !cs Discord instead of here
!cdisc *
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Reason I asked here as it's not directly related to the networking, but in general that a field from an object can be printed out correctly, but then be written to a stream as 0 in the same function scope
Actually, I should also just dump the bytes received on the server's end and just hexview it
You could move it below, and set the anchors to stretch/span the full width or be specifically positioned to the bottom of it
I can't change the position of the heart
Then you would change it through the layout component on your parent
okay just saw there is a little menu for padding but it was collapsed
thanks!
My hearts still overlap in full hd and overlap more the higher res I go
Did I forget something or is there a different way?
Do you have a Canvas Scaler setup on your Canvas?
nvm I'm an idiot, of course it doesn't save my value if it writes to the stream before I change the value 
for some reason my clamp teleports camera rotation, and teleports only when im moving my mouse left
and i cant find where exactly i make a mistake
Yeah, I think it is setup well
Looks fine to me, if the layout is attached to your text, maybe try a empty transform instead to put the hearts in and have that as a child of your text
Hi! I am trying to layer different settings on top of each other but for some reason I am not able to change any settings in my inspector. Can someone help me out?
its split in different scripts but this is the base settings:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class NoiseSettings
{
public float amplitude = 1;
public float frequency = 2;
public Vector3 position;
[Range(1,10)]
public int numLayers = 1;
public float persistence = .5f;
public float baseFrequency = 1;
public float minValue;
}`
this is where the settings will be called:
`NoiseSettings settings;
public generateNoise(NoiseSettings settings){
this.settings = settings;
}`
and here is where the array should be loaded:
`ShapeSettings settings;
generateNoise[] generateNoises;
public ShapeGenerator(ShapeSettings settings){
this.settings = settings;
generateNoises = new generateNoise[settings.noiseLayers.Length];
for (int i = 0; i < generateNoises.Length; i++){
generateNoises[i] = new generateNoise(settings.noiseLayers[i].noiseSettings);
}
}`
For reference: I am a coding noob. And this mostly consists of a tutorial: https://www.youtube.com/watch?v=uY9PAcNMu8s
In this episode we'll create a noise filter to process noise, and layer it for more interesting terrain. Episode 04 is out for early access viewers here: https://www.patreon.com/posts/21079771
Noise script:
https://github.com/SebLague/Procedural-Planets/blob/master/Procedural Planet Noise/Noise.cs
Get the project files for this episode:
ht...
there is something missing, here is the code where I say that I want this as an array:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu()]
public class ShapeSettings : ScriptableObject
{
public float radius = 1;
public NoiseLayer[] noiseLayers;
[System.Serializable]
public class NoiseLayer
{
public bool enabled = true;
public NoiseSettings noiseSettings;
}
}`
Moving my question here as it seems this is more general and not beginner:
I'm trying to create a custom menu by overwriting bits of the IMGUI. The first part is to simply implement a background image to a box control:
boxTexture = ResourceUtils.LoadTexture(ResourceUtils.GetEmbeddedResource("Resources.background.png", null));
boxStyle = new GUIStyle(GUI.skin.box);
boxStyle.normal.background = boxTexture;
This works as expected. However, something seems to affect the brightness of the image or menu when called within the game. I thought this might be GUI.color, GUI.backgroundColor and / or GUI.contentColor. So I tried several ways of changing those to color with 0 alpha (resulting in invisible menu), color with 1 alpha (resulting in color overwriting background image completely) and Color.clear also resulting in invisible menu.
My question is: How do I stop IMGUI "somehow" affecting the background image? See screenshot attached to this message.
hello i have a question
how to transfer the camera through a webservice. Do I have to go through a render texture?
or directly via the camera trying to have in both cases an array of bytes
you mean unity? or some package?
no body can help me?
What do you mean with webservice?
who cares what will become of me what worries me is how to convert (camera -> to array bytes) or (renderTexture to -> array bytes)
If you're just trying to convert an object to bytes.. Google would yield you immediate results.. example https://stackoverflow.com/a/10502856.
I'm going to try that I didn't think about it at all, really not stupid and I'm rebuilding on the other side
thanks
Reminder that object references/address and ids will be different on both ends.
I have a save and load script that makes a file using application.persistantdatapath but when I export it to universal windows platform it only works for the pc version but not the xbox
if you are going via web best option is RenderTexture->Byte[]->Base64 string
hey, these 2 lignes doesn t turn the object around the same axis, and i wan t to make the second ligne has the same axis as the first
transform.localRotation = newRotation;
gameObject.GetComponent<Rigidbody>().MoveRotation(newRotation);
i try with that code
and
Not a good plan, how do you expect what's on the other side to understand the output from BinaryFormatter?
Hi! Why can a callback from .jslib not be called?
I've put it in Assets/Plugins folder, and it is called when needed (there is console.log), but there is no callback
I tried console logging callback and it is "47425"
how do i make a game like this one
This is not the channel to ask about how to make TikTok games. This channel is for questions related to Unity coding issues or concepts
its not a ttgame
If you're unsure how to work with Unity, there are free !learn tools
🧑🏫 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/
Either way. I've seen these type of games pop up in TikTok streams to often 😄
public static Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
ok, so you need your receiving code to take the Base64 string from the web and convert it back to a byte[]
problem is, with your setup, you will end up with a RenderTexture object which you will not be able to use. you need to send the contents of the RenderTexture
what is the error here?
unity version - 2021.3.18f
urp project
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
[VolumeComponentMenuForRenderPipeline("Custom/Ben Day Bloom", typeof("UniversalRenderPipeline"))]
public class DottedBloomEffect : VolumeComponent, IPostProcessComponent
{
public bool isActive()
{
return true;
}
public bool isTileCompatible()
{
return false;
}
}
well, what is the console telling you?
remove the quotes
you put in the actual class there
oh...
class?
literally just remove the quotes
UniversalRenderPipeline
typeof takes that identifier and turns it into a piece of data that the annotation needs
ooooh... i understood now
the class..... like DottedBloomEffect?
no, UniversalRenderPipeline
dis one 😅
well, look at your spelling
you can't just randomly change the capitalization and expect it to work
the IDE's suggested auto-fix for the interface problem should create two methods
(including the override keyword in their declarations)
this is the "potential fix"
there are two potential fixes
it looks like the second option is the one that explicitly names the interface that we're implementing the functions for
I'd go with the first one.
this is the first one
oh right, brain fart
you wouldn't use override here
anyway, yes, that looks reasonable
notice how the capitalization is different..
this solved my problem
i usually just let the IDE generate the methods and then fill them out myself
In unity, I am trying to read pixel values from a texture,
but it seems like the pixel values are wrong?
specially compared to the same file being read using
Bitmap API in System.Drawing
here is how I read both:
Texture2D tex = null;
byte[] fileData = File.ReadAllBytes(img2Path);
tex = new Texture2D(640, 640,TextureFormat.RGB24, false);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
tex.Apply();
and then to read pixels
I do:
tex.GetPixel(x,y);
I compared the first few pixels, with the first few pixels from the
Bitmap image, and it was very different.
any ideas?
using var image = Image.FromFile(img2Path);
Bitmap bitmap = image as Bitmap ?? new Bitmap(image)
BitmapData bitmapData;
if (bitmap.PixelFormat == PixelFormat.Format24bppRgb && bitmap.Width % 4 == 0)
{
bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
unsafe
{
data = new Span<byte>((void*)bitmapData.Scan0, bitmapData.Height * bitmapData.Stride);
}
}
then I do read values from the data
as follows:
data[0] = b
data[1] = g
data[2] = r
and so on,
the values for
Bitmap are:
0.3 031, 0.32
but for the texture they are very different. (0.008, 0.023, 0.31)
how i keep the texture of camera without put a rendertexture? a i can screenshoot ( it's good or bad idea)?
visually do you see a difference?
I believe it has to do with sRGB but that is my only hint
the colors yes, but when I render or save the image it does not seem much different (There is some differences definitely in the Yellow component, but the output image is definitely acceptable)
I heard somewhere unity Does sRGB by default, is there some where to turn this off, just to be sure I am not doing anything weird?
there was some conversion util somewhere in unity internals, and its a common pain point
i cant recall solution but there are various problems related to linear/gamma
if it is a bit of different implementation I don't mind it honestly, like I don't care much about 0.31 vs 0.32 or so, but I definitely care if it is doing 0.32 vs 0.008
if they visually look the same, its weird, maybe the corners are different?
coords origin
not exactly the same, as I mentioned it is a bit different,
but I need it in RGB space, because I want to do ML detection on it. (and the model was trained on RGB)
that is too much of a discrepancy imo
what do you mean?
orders of magnitude difference, i dont think sRGB can account for that
Hello i'm all new to this but i need to think of a login system for a software wich has an already build api and database, i want to do a login with discord but i have no idea how hard or even if it's possible
I am a bit lost, I thought (and sorry if I misunderstood you) you agreed than the difference is probably gamma correction?
so what I asked was how to turn it off.
or did you mean something
yeah I saw your message, but I don't think it is?
well, I checked only the bottom and top corners,
I will check the other two, but it is a bit unlikely I think.
ah you had different order there missed that
yeah now srgb seems more realistic
disabled sRGB for the entire project, and that definitely was it,
the model seems to be working now.
is there a way to disable it on a texture basis? because I don't want to keep my sRGB disabled. (Tho this might not matter in the end, as I can write a converter back later on, but will help me significantly in my debugging process right now)
probably yes, the flag is available in the importer, maybe there is an arg in load bytes somewhere
I will look into textureImporter (whichp popped in google but hoped there was something just like:
sRGB = off:
sRGB = on;
Thanks!
importer is editor only
oh, that is why I was struggling to get something from it... that is useless because in the end I would want to get them from camera feed.
How resource intensive is it to call a SphereCast every frame for a couple of seconds?!
i mean that there is a lot of editor things of which you only get scraps at runtime, i would first apart from googling read through all the overrides for all texture byte loading methods
there is also i think something like EncodePNG maybe it has decode and i think there was some static util available for this
ImageConversion class has a bunch
EnableLegacyPngGammaRuntimeLoadBehavior
may be useful
a non alloc version should be fast
what does a non-alloc version mean?
non alloc means non allocating
meaning it doesnt allocate new array to store results every time it is called
you create an array/list and provide it to the method
mhm...
so what can't i do with this sphere cast, that i could do with a normal sphere cast?
it should be identical apart from non alloc part
most casts/overlaps have non alloc versions
dose someone used balser dll in Unity?I can not find the way to use it. could someone can help me? thank you
I want to use Unity to connect the Balser camera and I download the dll from the Balser web, and placed the dll into assets/plugins folder. But I can not using the namespcace🫠
Hey umm so i have grid system setup and I want a mechanic to know which tiles player is able to 'see', even tight angles count.(here is some drawnings to visualize the idea).
What would be easiest way to approach this. Its not like i couldnt do some kind of raycasts, but i have to get every tile in the way before wall+i would need to cast like 100 of them to different direction for being able to be precise enough.
So I just thought if there is some good solutions/methods for this kind of stuff already so i dont have to think with my own brains lmao.
Also player is always centered in some tile so casts are sent from a middle of that tile, so like u cant be inbetween of few tiles
(And also i dont know if mathematically that bottom right corner should be seen from there, just tried to show example that i want it to also spot rly small gaps and see throught them)(propably not tbh)
Do you only care about seeing other entities?
Or do you need to do some kind of fog-of-war system?
Fog of war
I'd start with raycasts
Yeah, propably the best option
since you're using a grid might as well do it the mathy way
Oh thx, i take a look on that too
OH NO
I've been having issues getting a WebGl build of my project working on unity play. The screen looks like this and dosent load in the game and returns this message in the console.
im assuming its because of the memory leak
but i cant figure out for the life of me how to get rid of it
I tried
looking it up and install a new package to trace the leaks but i dont know where to go from there
First things first, make sure it's the actual issue. Open your browser's dev tools window and reload the page, watch for errors
Also it's probably not a code issue and better asked to the experts in #🌐┃web
ok
for an inventory system, I've seen people make every inventory cell a button, and I've also seen people just make them containers with an image component. Are there any unforseen upsides or downsides to either of these approaches? just wondering if one is "better" for any particular reason
Both sound like similar approaches
A Button is little more than a Selectable with a UnityEvent for the PointerClick event
It kinda just depends what kind of functionality you need on the inventory slots
could you elaborate? I genuinely thought that was all they were haha
Elaborate on what
how buttons are more than a selectable with a unityevent
So I have a function that needs to find every tile in a grid array that is Null, but the grid array is 2d, so I can't use Find, how do I do it?
foreach (Tile tile in Array.FindAll<Tile>(grid, tile => tile != null))
{
//Do something
}
for (int i = 0; i < grid.GetLength(0); i++) {
for (int j = 0; j < grid.GetLength(1); j++) {
if (grid[i, j] == null) {
// do something
}
}
}```
ahh, I see, that makes sence, thanks
Or, keep the foreach which will flatten the array and check each element for null like above.
foreach (Tile tile in grid)
{
if (tile != null)
// code
}
problem with foreach is it's harder to then do something like grid[i, j] = something;
but it depends if you need that or not
or to access the i, j
yes, I do actually need the i and j, just forgot
Hello does the Physics.Raycast method work by simply doing a ray triangle intersection test of every triangle in the scene?? or how does that shit work
No - first off it will do broadphase collision tests against the collider bounds using the spatial partitioning structure of the physics scene
that narrows down which colliders it needs to test
then it takes that smaller subset of colliders and tests each one individually - but the algorithm for each depends on what kind of collider it is
SphereColliders and capsule colliders don't even have triangles for example
makes sense
but with a mesh collider it would need to make ray triangle intersection tests tho right?
Spheres would just check if the intersection is in their radius, IIRC
It also checks the AABB before checking any individual triangles when it comes to MeshCollider
Possibly? Not really sure how PhysX implements it. The code is open source though
I have a UnityEvent<object> variable, and I am setting a method call for it in the editor MyClass.SetEvent(object context), I know I am invoking the UnityEvent with an object but my debug in SetEvent isn't being called. Any idea why this might be?
I am asking cause I am searching for an efficient way to handle raycasting inside of a shader
so thats why
you're using object as in System.Object?
can you show the code?
yes, the method is showing up under Dynamic Object in the inspector for Unity Events
ok that should work in general
ok so with that it narrows it down to which object, but it then still needs to do a ray intersection test for every triangle of that object?
I guess, since RaycastHit can store triangle info
Ah thats for single triangle
Yeah it's unclear if that's called for every triangle in a mesh
But probably yes, I don't think it splits the meshes into subsets of vertices/tris
it's also kind of unclear what data structure PhysX uses for mesh colliders
So I would rather have multiple smaller MeshColliders than a monolith
I know that convex colliders are limited to like 255 triangles or something
that could definitely be a limitation due to needing to test every triangle in such operations
// variable
public UnityEvent<object> OnPerformed;
// Invoke
input.performed += (context) => {
Vector2 arg0 = context.ReadValue<Vector2>();
Debug.Log("OnMove" + arg0);
OnPerformed.Invoke(arg0);
};
// Dynamic method added to UnityEvent
public void SetEvent(object context) {
_context = context;
Debug.Log("Setting Context = " + context); // This isn't showing up in logs
}
Wait why am I casting to Vector2 there one sec
Is "OnMove" being printed?
I am just thinking cause I want to do ray intersection tests between a ray and a set of triangles which makes up an object, in a compute shader or something. So just thinking if it would be costly to do it by simply checking each triangle
Can you have each thread check a triangle
not at once there wouldn't be enough threads, but yeah I think so
Yes it is, but the "Setting..." isn't. The cast to vector2 doesn't seem to be effecting it(it is just automatically being cast to object for the invoke call).
RaycastHit
.barycentricCoordinate;
.textureCoord;
.triangleIndex;
Should be enough to get you started in triangulating a point on your texture, no?
uh, texture? I was more like thinking of sending a buffer of vertex positions to the shader and then.. that would be all I need right?
Debug.Log(OnPerformed.GetPersistentEventCount()); // => 1
So their is a registered listener, just no clue why it isn't being called
Maybe? textureCoord gets you the coords of the UV texture btw, not the main texture. Not sure if you can do anything with that. Oh and this only works for mesh colliders of course
I am confused to why you are refering to textures? For what would I need a texture?
I have no idea
You said you wanted to do vertex displacement relative to a point, so it might help locating that point on the mesh
The docs seem to be doing setup of the generic UnityEvent slightly different so gonna try that first.
https://docs.unity3d.com/ScriptReference/Events.UnityEvent_1.html
- When a C# dll is put into a Unity Project, is it compiled again, or ignored altogether?
- If I put the dll in a folder which belongs to an assembly, it does not seem to be getting packed under that assembly
- If the answer to the above questions is (yes and that's correct), is there any way to make the API under the DLLs not show up in another assembly defined in the project?
I'm having trouble with an error:
"The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(Dog) weight"
Here's some sample code to reproduce it:
public class Animal : MonoBehaviour
{
public int weight;
}
public class Dog : Animal
{
//int weight;
}
The Animal.cs and Dog.cs are attached to separate objects in the scene. Can somebody help me understand what's wrong?
With weight in the child class commented out you shouldn't get that error anymore
Reimport them
??= How does this operator work?
Funky null-coalescing-assignment operator. If what's on the left of ??= is null, then it evaluates what's on the right, and puts it into what's on the left
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
don't use it for types deriving from UnityEngine.Object though
Suppose I have a list of references to ScriptableObjects (which are specific assets on disk). I want to serialize that list and retrieve it later.
Naively serializing the list just spits out Instance IDs.
Am I going to have to slap a unique key on each SO and then have a class that can look the SOs up with that key?
The assets will not be changing (as in, their GUIDs are gonna stay constant)
I have the following code which should take a rect transform and align one of its corners exactly with the corner of a target rect transform (vertTargetTransform). When I run this code the rects are aligned perfectly on the x axis but one corner is below the other... When I debug the xDiff and the yDiff they both say 0 even though the rects are clearly misaligned. I am doing this on a Screen Space - Camera canvas. Any ideas why this isnt working?
{
Vector3[] corners = new Vector3[4];
Vector3[] corners2 = new Vector3[4];
myTransform.GetWorldCorners(corners);
vertTargetTransform.GetWorldCorners(corners2);
corners[cornerToMatch] = canvasTransform.InverseTransformPoint(corners[cornerToMatch]);
corners2[cornerToMatch] = canvasTransform.InverseTransformPoint(corners2[cornerToMatch]);
float xDiff = corners[cornerToMatch].x - corners2[cornerToMatch].x;
float yDiff = corners[cornerToMatch].y - corners2[cornerToMatch].y;
Debug.Log(xDiff);
Debug.Log(yDiff);
Vector2 targetPosition = new Vector2(myTransform.anchoredPosition.x - xDiff, myTransform.anchoredPosition.y - yDiff);
LTDescr tween = LeanTween.move(myTransform, targetPosition, moveDuration);
tween.setEase(LeanTweenType.easeOutExpo);```
it'd be nice to be able to just write out a list of GUIDs, but I'm very fuzzy on how that'd work.
pretty sure you need to use UnityEditor to mess with the actual assets
Hi guys, I have issue with my project build: I build the project using unity 2021.3.23f1 from Windows to mac.app, but then when I try to open it on every Mac it doesn't work...
Could somebody help me please?
When I click the file, nothing happens
The file doesn't open
Yes
Anyone know why my particles collide with the ground but then immediately fall through it ?
do you get anything if you open the terminal, navigate to the application, and then try running:
open mac.app
?
There is a message "the operation it can be completed because an error occured
this is a code channel. perhaps you want #✨┃vfx-and-particles
alternatively, see if this does anything:
./mac.app/Contents/MacOS/mac
note that the last part may be different
i'd just tab-complete it
this will try to run the executable directly
I'm not sure I've seen this exact thing pop up. I usually have problems with the file being quarantined, or the executable in there not being marked as executable...
I dont know uWu
It might be a problem about security?
did you try running this?
note the . at the front
No, now I'm trying
i'd just punch in ./mac.app/Contents/MacOS and then hit tab to see what it completes with
nothing it doesn't work
so the console printed absolutely nothing?
you ran that command, and you just got a new blank prmopt
can you copy and paste the line you ran?
I restarted the mac and , I don know how, It WORKS!!
splat
very strange
well, you'll want to check on other macs, if you have access to more than one
Thanks a lot for the support 😎
The main problems I run into are:
- the app file is quarantined
- the executable is, for some reason, not marked as executable
(maybe another instance of Apple trying to save me from myself)
crazy ahah
Didn't solve my issue, and also seems Unity can serialize the straight generic variable now?
Issue related to that code. I am calling invoke on a UnityEvent<system.object> variable. I have a Dynamic method set in editor for it, but the method debug isn't happening(aka method isn't being called on invoke). There is a listener registered, and it's state's readout is runtime.
i have a isdead variable = false but when i log it i says directly is true
show code
i'm just going to take a shot in the dark here
public bool isdead = false;
it's true in the inspector
its private
okay, that rules out that avenue!
but i have this code
show your code.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("platform"))
{
if (collision.contacts[0].point.z > transform.position.z)
{
CheckDeath();
}
}
}
// Set dead state
private void CheckDeath()
{
isDead = true;
}```
📃 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.
You set it to true each frame in Update (you call CheckDeath there)
"CheckDeath" is a very misleading name, yes
sets bool to true
logs bool
why is this bool true?
which is probably how this happened
Yeah it doesn't check, it kills
i remove out of the function
i'm going to check your blood pressure pulls out a sword
how to check whenever i check the front of a object
Otherwise you can check the angle from the current object's forward and the collision.
This issue is still boggling my mind. If someone has a free moment could they check if it is working for them to use a UnityEvent<object>
i made collision on the x-as smaller to avoid sideways collisions
How would I go about making a deep reinforcement ai?
you asked this earlier and you got an answer: do some reading
Cool, I figured out my issue. I had two objects with the components on them in scene, I was setting up the wrong one, while the other was getting called.
oh i see you actually did post in the ML channel already. in that case, stop crossposting
(which is exactly why crossposting is bad!)
nobody is responding and I’m pretty sure nobody will
more confusion
perhaps this is because nobody wants to teach you the entire subject when you have not demonstrated that you've put in any work so far
that doesn't mean you should ask in unrelated channels. either be patient or do some research (which is what you'll need to do anyway)
I’m trying to research but I can’t find any tutorials or such
!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.
oh...
i meant actual research. not looking on youtube for ready-made tutorials that just have you repeating exactly what they do
yes
the more complex your task becomes, the less likely that someone will have made a neatly packaged tutorial for you
with that said, I'm pretty sure I've watched a few videos talking about reinforcement learning in Unity...
im not able to researched it out so help, i want to find a class/object by value(example: string)
here is my example script: https://paste.myst.rs/dtvg5d9o
a powerful website for storing and sharing text and code snippets. completely free and open source.
sounds like you want a dictionary
Dictionary<string, TheClass> will let you store and look-up TheClass instances with string keys
yeah it's either that or they'd have to compare the value stored in the class's field with their "entered" value
indeed, running over a whole list
me google c# dictionary then
Okay, why do so many people think their question is general when it is a beginner concept of programing
😆
dictionary actually a little more advance I'd say
but once you figure them out you'd use them like candy
To a beginner - almost everything sounds advanced. It's a bit of a Catch-22
Fair
I think it'd be better for the channel to be:
"a place for beginners to ask questions"
rather than
"a place to ask beginner questions"
coder-beginner
coder-generalist
coder-advanced
thanks for making me acknowledge dictionary , there is solution i figured out: https://paste.myst.rs/s5g5gs9y
a powerful website for storing and sharing text and code snippets. completely free and open source.
you're treating your dictionary like a regular List so it being a dictionary is pointless
umm its just example
ah, so in your actual code you'll be actually using the dictionary like a Dictionary and not just like a list? if that is the case, then why are you doing it differently in your example?
umm this example is made to... show how i want it to work? confuses
and again, you are treating your dictionary like a list. you can accomplish the exact same behavior just by using a list and comparing the value to the property/field
i dont think i even know what property/field is and how it works shrug
well a field is a class-level variable
and if you don't know what that is then you may be in the wrong channel
i should got to beginner?
for your future questions, probably
but if the way you have this set up works for you then you do you. it's just not doing anything that requires you to be using a Dictionary over a regular List
here is what that would look like using a List instead of a Dictionary
https://paste.myst.rs/efzzwl5m
understands the code thanks
and if you were curious how it would look if you were actually using the dictionary as a dictionary and not just as a List: https://paste.myst.rs/rus0y0bo
of course there's also the TryGetValue method which may even be more appropriate here and that would literally just be dictionary.TryGetValue("123", out theClassObj);
I have a script which makes a player spawn at an object in my scene, and it's saying that 'Transform[]' doesn't have a definition for 'Instance'. What should I change? void OnServerSpawnPlayer() { var spawnPoint = ServerPlayerSpawnPoints.Instance.ConsumeNextSpawnPoint(); var spawnPosition = spawnPoint ? spawnPoint.transform.position : Vector3.zero; m_ClientPlayerMove.SetSpawnClientRpc(spawnPosition, new ClientRpcParams() { Send = new ClientRpcSendParams() { TargetClientIds = new[] { OwnerClientId } } }); }
public Transform[] ServerPlayerSpawnPoints;
are you certain you have the right type there? Transform contains neither an Instance property nor a ConsumeNextSpawnPoint method. and an array of type Transform certainly wouldn't contain either of those either
or are you perhaps accessing the wrong variable
What would the right type be?
how should i know? i assume it's probably some type included in whatever networking library you are using but i have no context for your code other than what you have just shown
https://paste.myst.rs/y8iww5dw is the code.
this doesn't tell me anything about where you are expecting that property and method to be
have you just gone and copied code from some random tutorial without actually modifying it to work with your existing code?
No.
then what type are you expecting to be a singleton Instance with a ConsumeNextSpawnPoint method?
I don't understand, why is public Transform[] ServerPlayerSpawnPoints; not in the code you sent
Is it in NetworkBehaviour or something
No, there's just a bit of code in between the two lines I sent that wasn't relevant.
right but the code you pasted in the bin site is presumably the whole class, right? but the only Transform[] in that class is called spawnPoints not ServerPlayerSpawnPoints, so where is ServerPlayerSpawnPoints or is this some other class where that line actually does work?
but I'm looking at the complete code you linked, not your two lines
Ok, I'm going to do something easier and just put a capsule collider instead of a sphere collider on my player.
Machine learning chat hella dead
and yet that still doesn't mean you should start posting your machine learning question in irrelevant channels like you were doing earlier
the last post besides me was 5 days ago 💀
where else could I post my question because clearly nobody is going to answer in the ML chat
your question is just "how to do machine learning"
so maybe you should do some research like i suggested before
could try the forums since they are usually better for more slower, complicated questions
Ive done a lot of research, I’m sort of new to Unity and all and I was just wondering how to get started with machine learning
okay thank you
new to unity
as i also pointed out hours ago, machine learning is not a beginner topic. maybe learn how to use unity and probably also how to code if you don't already know. then at least the research you do won't just need to be "how to do machine learning but spoon feed me the info because i don't understand the context"
any double tap detection that works with getaxis? I already know how to detect ones that use keydown but detecting getaxis seems like more complex since it needs to detect the "speed" changes.
I think I can figure it out eventually, but if there's already working ones then why should I reinvent the wheel, right?
Use GetAxisRaw
So you don't have to deal with the gravity/acceleration nonsense
That what I tried first, but seems like there's a delay in value changes.
Like instead of getting the raw value, it just step/round the value
GetAxis has the delays. Raw is instant
🤔 Let me try again, maybe the problem is in how I combine the raw input and the smoothed input (I use the raw input for double tap detection and the smoothed for animations)
Yep it does works 😅
I forgot to change the stored last direction from the smoothed input to raw input
Thanks 🙂 👍
ok, I'm not sure if this is the right place but i can't fingure out how
ok, so if i wanted to use this function
would the only way be to move the package into my actual project?
PlayerData is a scriptable object holding playerData, if i try to pass level+1 into the Load Scene line the scene this script runs in gets stuck loading
public PlayerDataManager PlayerDataManager;
// Start is called before the first frame update
void Start()
{
var level = PlayerDataManager.currentLevel;
var World = PlayerDataManager.currentWorld;
if (PlayerDataManager.currentLevel == 0 && PlayerDataManager.currentWorld ==0 )
{//new game
PlayerDataManager.currentLevel = 1;
PlayerDataManager.currentWorld = 1;
level = 1;
SceneManager.LoadScene(2);
}
else
{
}
}```
Not seeing anywhere you're changing scene with some sort of dynamic data
im no c# master but how does this even compile?
"public PlayerDataManager PlayerDataManager;"
you can name fields this way but I wouldn't recommend it
As it will hide the type name going forward
Oh i did not know that ill change it,
oh oops pretend that SceneManager.LoadScene(2) said SceneManager.LoadScene(level+1)
that's not any different at all
unless you also made other changes besides just that
such as eliminating the if statement(s) etc
Oh wait nm im stupid i did change something i forgot about
i added that level = 1 from when it was crashing cuz i though i had deleted it instead of commenting it out when i was trouble shooting but i just never added it
public PlayerDataManager PlayerDataManager;
// Start is called before the first frame update
void Start()
{
var level = PlayerDataManager.currentLevel;
var World = PlayerDataManager.currentWorld;
if (PlayerDataManager.currentLevel == 0 && PlayerDataManager.currentWorld ==0 )
{//new game
SceneManager.LoadScene(level+1
);
}
else if (true)
{
}```
had that originally and I realize its because level is set directly to PlayerDataManager isn't it?
NM nm im just stupid I see the issue now...
this scene is index 1, and i forget to set level to 1 so level is 0 so its loading level+1 which means its trying to load the same scene again each time it starts
I have a compute shader, that I have used and tested on a RenderTexture, I now try to use it on a webcamTexture,
but when I try to bind it
it says:
Property (Output) at kernel index (0): Attempting to bind texture as UAV but the texture wasn't created with the UAV usage flag set!
the type in the shader is
RWTexture2D<float4>
unlike renderTexture,
There is no
enableRandomReadWrite = true
inside webcamTexture
Hello there, I am currently looking to implement some basic debugging info into my game such as video memory usage and ram usage, I have found that Profiler can help me but Im not quite sure which of these methods correspond to what I need, for example , what can I use for Ram here?
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.html
I'm creating a package. What should the asmdef's root namespace be? Should it be empty or the name of the package?
I don't think that you can write to it from the GPU. Same as with a regular Texture2D.
Also, one of my packages is a [ReadOnlyInspector] attribute. Should I keep it in the default namespace so users don't have to using it? Or should I put it under its own namespace? I'm thinking the latter for cleanliness, but on the other hand, adding a whole using statement for one little attibute in every file you want to use it on seems tedious
Or should it be myname.mypackage?
Are you planning to incorporate it in a production build?
Generally, I see myCompany.myPackage.branch, and for parts that are important to the whole package, is often in a core, so you could put that attribute inside of for example SomeCompany.AwesomePackage.Core, I feel like if someone is adding your package to their project, theyd expect every script to be a part of a namespace in your package, which also helps for identifying which assets/scripts are actually a part of your package as opposed to something they wrote or another package
For an asmdef, unless you expect whoever will be using this package to be extending it with their own classes and want it to be a part of the same namesapce, or your not done with it yet (to me, it sounds like your package is already done?), I dont think giving the asmdef a namespace would make much of a difference, if all the scripts in your package already have a namespace anyway
Okay, then I will just read from it I guess.
Hi! I have problem but i don't know where exactly i have to ask this question. When i build game, i can hear all audio sources no matter where they are placed, but in editor everything is correct. What can cause this error?
Pretty much, I'm aware there are some stuff that can only be used with developer symbols, but I just want to know how its done
Seems like ProfilerRecorder is what you should have a look at.
It seems like the marker names/profile counters can be found in the manual of each profiler module.
Learn how to get precise performance metrics while your project runs on your target device. In this session, we use Unity 2020.2’s new runtime ProfilerRecorder API to capture and display in-game profiling stats like draw calls.
00:00 – 02:29 Introduction and Getting Started
02:30 – 05:18 Showing Draw Calls
05:21 – 09:29 Profiling Custom Code...
This video and the debug overlay from here formed the basis of our runtime debug https://github.com/Unity-Technologies/FPSSample/tree/master/Assets/Scripts/Utils/DebugOverlay
this looks like what Im looking for, thanks!
If you want the full runtime debug experience
Thank you so much!
Still need help with that. Where can i ask this question otherwise?
That error warning is typically when u reuse a name that's already used
Unity has some reserved names like collider, name, rigidbody, etc - in general, its good practice to be descriptive with your variable names instead of just naming it as the component, for example "playerCollider" or whatever collider its meant to represent - the error seems to be from your PlasticSCM, without more context I couldnt guess what would cause it though
Someone else in here had the same error before, upgrading the version of Plastic seemed to fix it. Also others suggested to remove it
who can help me please
System.Convert.ToBase64String(txtVisu.GetRawTextureData())
i want send my texture in string Base64
but when i try with a simplle string ("text") it's ok
but with GetRawTextureData
output AABJkiRJkiS/B58H/////wAASZIkSZIkvwefB/////8A.......... why "/" ?
when output index 10 and 11
159 and 7
Hey,
How to reduce the amount of decimal points in a floating point number?
Like this
1.3450925
1.3450000
Maybe simply round it when you're needing to print it with string format else there's Math Round https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-8.0
For rounding during print use https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings for example num.ToString("N3");
or string.Format("{0.0000000}", Math.Round(num, 3));
Math Floor of your wanting to truncate https://learn.microsoft.com/en-us/dotnet/api/system.math.floor?view=net-7.0
hey does anybody know how to make a canvas pop up to enter a code?
Is this related to scripting? What have you tried?
i tried disable the camera when im on the box trigger
but its just stops everything
What do you mean by pop up? is the Canvas not active by default?
Just set it active and give it's input field focus
Show what you've tried (code).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Puzzle : MonoBehaviour
{
public Canvas canvas;
public GameObject player;
public Camera playerCamera;
private void Start()
{
// Get a reference to the player GameObject and camera component
player = GameObject.FindWithTag("Player");
playerCamera = player.GetComponentInChildren<Camera>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
// Set the canvas to active
canvas.gameObject.SetActive(true);
// Disable the player GameObject and camera movement
player.SetActive(false);
playerCamera.GetComponent<Camera>().enabled = false;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
// Set the canvas to inactive
canvas.gameObject.SetActive(false);
// Enable the player GameObject and camera movement
player.SetActive(true);
playerCamera.GetComponent<Camera>().enabled = true;
}
}
}
!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.
Maybe don't set the player inactive but instead disable it's renderer component - setting the object inactive may cause the exit condition to trigger.
ok
i try something else
i think i got an idea
where can i ask qeustions?
look in #🔎┃find-a-channel for the one that matches the question you want to ask then ask there
I'm trying to instantiate the object inside spawn object, but it seems to instantiate outside of it
Here's a code
Please configure your !ide before asking for help
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.
Your syntax highlighting is not correct
Or correct me if you do get proper autocomplete on functions such as GetChild, then it's fine
I did
If "enemy" is a prefab, your currently trying to set the parent of the prefab, and not an instance of it - Instantiate returns a GameObject, so you could instantiate into a variable, then set the parent of that variable instead, or Instantiate can also create an object into a parent provided as a second parameter, see the second overload in the docs: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
!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.
Hi, I'm new in this discord, but my teammate and I have a problem. We are creating a race on Unity. The textures of the circuit created are so good (my mate has a talent), so put the project as HDURP, but that makes the camera vibrate by not refreshing the project would need. At the moment, we have had to put it to RP to complete the game, but it is a pity that the work done is not appreciated. Would anyone know how to help us? We now we have to do something in the script part but we doesn't find anything (we are students)
You mean this one?
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
The camera is inside the vehicle (well, looking at the steering wheel)
You could use that one if you also want to specify a rotation with the parent, or just the parent if you want the rotation to be defaulted
ok
ok i got it to work now
does anybody know how to get your mouse out from the camera
and being able to click on the screen
sry for my horrible
english
Cursor.lockState = CursorLockState.none something along that
Is there a way, to make app self checking if there is new update ready on google play, so player will get in-game notification like "Hey! there is update to download!"
Here is a tutorial that explains this topic:
https://www.youtube.com/watch?v=TA8B_jmjhX8
Hello,
in this tutorial I will show you how to make in-app updates for your android games in Unity. We will focus only on how to force an update for your game.
Make sure to updload your game to the googleplay store!
Download the Unity Package here
https://developers.google.com/unity/packages#play_in-app_update
➤Follow me on Instagram : https:...
Ideas on how to make small TMP texts more sharp? Google gives mostly tips for the old Unity UI Text component, but not much for TMP.
Tried changing the font, it does get sharper with some other fonts but I think there is something else...
Oh, how i missed that. I've google this question and this video didn't show up
thanks you
Loll it was there since i created the project
Ah, this is why tutorials don't always work xd
The sharpness depends mostly on the font size. E.g. a huge font size with a small object scale gives sharper effects than a small font size with a huge object scale.
I have seen this on old posts for Unity UI Text but does no effect in my case (tried a 10x font size, 0.1x scale and reversed but litteraly the same results)
also AA is disabled in my URP so it should not be related
Why does Unity precede fields with m? And is there an official Unity coding conventions
To me these look exactly the same
have you tried adjusting the settings on the text material? you can control softness (0 by default, probably not gonna help here) and dilation (which will make the text become thicker or thinner)
the latter might help
dilation at -0.19 vs at 0
note that if you just adjust the one that's on the text by default, you'll be changing the material for all text...so you might want to make a separate material 😛
i was looking to see if there was an option for controlling hinting, but I'm not sure that's a thing for this style of font rendering
this does help a bit around -.2 but you can still see the text kinda weird "mushy" borders (renders perfectly on scene view when zoomed in but this is not rendered the same way)
is your game view rendering at a fixed resolution and getting scaled?
i.e. is the Scale slider not at 1x
it is at either 16:9 or 1080p rendering and always 1x scale
made any changes to the shader?
What does this have to do with coding
where should this one go, actually?
no, standard shader
right, not always sure where to post on this discord I will move it there
is there a difference between unity random.range(-1f,1f) and random.range(-1,2)? as in the difference between using the int random vs the float random? if I have the choice which should i take?
yes there is a difference.
The difference is one is an int and one is a float.
the int version only returns integers
The min and max values are the same, but the first one can return fractions such as 0.0123f
apart from the int-float difference. I only need full values anyway
also int is max included, float is max excluded iirc (might be reversed)
If you need full values, then there is no point in using floats.
but only with floats
ah yeah, forgot to specify :p
it's very unlikely for the inclusive float range to matter, but it is a possibility...
there is no difference other than the int-float difference but that's a huge difference. In fact Random.Range(-1f,1f) will only extremely rarely generate -1 or 1 whereas Random.Range(-1,2) will generate -1 , 0, and 1 1/3 of the time.
this is why my example is as it is ;D yes, so i got it. when i need ints anyways, always use int version of random.range. my specific example would be
var random = Random.Range(-1f, 1f);
return random >= 0 ? 1 : -1;
the odds are roughly..i dunno, one in a few billion
so i go there with int version as well
So even if you';re doing Mathf.Round or Ceil or Floor, you're going to get very different numerical distributions with the float version vs the int version
so it's not only more code but also probably not the result you want
indeed
use the integer version to pick things
use the float version to place things
thanks!
that reminds me of something really useful
you can use R(-10,10) to get a random value from -10 to 10 in the inspector
if you're multi-editing, each object gets its own value
thats neat
Hey guys , is anybody here familiar with AstarPathFinding? I am trying to use it for pathfinding in 2D and it works super well.
But there is a problem where the agent doesn't really "care" to collide with stuff unless its its super in him . Like on pivot I think. Anybody knows how to fix it? Thanks in advance :) tag me please <3
A* pathfinding is quite a popular algorithm and has plenty of different implementations. Issues may vary depending on the version.
If it's based on the NavMesh, you should adjust the agent settings in Window/AI/Navigation window. The bigger the radius of the agent is, the further your AI will stay away from obstacles.
Thanks but I am not sure if its based on navmesh but I don't think it is
If you haven't generated any NavMesh, then this algorithm probably doesn't use it and is based on something else. Can you post the link to this asset?
jesus don't crosspost
Holly chill
I asked before and no one answered so I asked here
I half got it to maybe work
I suppose you can increase Diameter in GridGraph.
No really xd , It just makes the grid "cells" bigger diameter which is not something that will help
I found a way for it to work
Kinda
it's both node size and the diameter on the collision settings of the gridgraph as i've already pointed out in the other channel
The is not 100% correct tho and it doesn't not help me to solve the problem
prove it
K
because it is correct for what you've described as the issue
Let's say ill increase the diameter to 5 okay? what shall happen then?
I am 100% wrong
then it will expect your agent's diameter to be 5 nodes wide. which will mean that there should be a gap 5 nodes wide around obstacles to make your seeker actually go around them
Lmfao
Anyway
Mistakes happen
Thanks for the help @somber nacelle But I will sidenote that even if you are not trying you are a bit aggressive lol . it's not a bad thing just something that you should note for later :) Have a good one cya!
maybe next time stop expecting people to just guess at what your issue is?
You are doing it again and I won't argue I'm just letting you know! I hope you have a wonderful rest of your week!
I need assistance and I feel like im going insane. I have a player who has a gun (2D Top Down). The gun has a shoulder behavior, where its not DIRECTLY apart of the character but a child that rotates around the parent. I want the sprite to flip when the gun is on his left but it absolutely won't. If anyone can help me, I can DM you the code I have for you to look over rq
if you want to share code, you do not need to DM it. follow the bot's instructions for sharing !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.
you're comparing transform.rotation.z which is part of a quaternion which means it can never be greater than 90 or less than -90 considering quaternions 1) do not deal with angles in degrees 2) are normalized
i'd say switch to using transform.eulerAngles.z but you really shouldn't rely on eulerAngles for logic, you could instead have this component communicate with whatever component is rotating your player to flip it when necessary
I gotcha. I did switch it up to Eulers, and its still not working but it HAS improved and seems to be at least responding now. I can def work with this. I appreciate the help
euler angles are annoying because they can be discontinuous
you do a slight rotation and bam, all three components changed significantly
Yeahhh, they def are finicky, I did figure it out though, all is working well. I decided to get rid of the euler angles bc of that actually and used the local position point in comparison to the parent instead. Much smoother than trying to deal with the angles. Thanks for the help and info!
I'm still hemming and hawwing about this for a save system. I could use some hot takes on the matter (:
I'm a little unclear on how the conversion from the unique id (e.g. a GUID) to the scriptable object asset would work
I guess it'd be a Resources.LoadAll<TheSOType>()
and then just make a dictionary out of that
oh, yes, that's absolutely how that'd work 🦆
Look into the Addressables system
or, perhaps, something Addressables related? I just need to fetch all scriptable object--
ah, there it is :p
I have it in the project already for Localization. I will give that a look.
I imagine this will be a relatively simple application of them. I'm not exactly loading hundreds of megs of assets from a remote server here.
One question about that: Would it be possible to store and load references to specific Addressable assets? i.e. could I store a reference to an asset and then use that to pick the same asset later?
something along the lines of looking at the asset's GUID in-editor
or do I need to go ahead and put a unique key on the scriptable object?
the intended application here is remembering a list of save points you have reached
each one will have a reference to a scriptable object (that is unique per-save-point)
currently that object is just
using UnityEngine;
using UnityEngine.Localization;
public class SavePointSpec : ScriptableObject
{
public LocalizedString label;
}
i have this script that makes a grid of tiles then adds each tile to a Dictionary with their key being thier position, I just changed it such that each tile is a child of the "grid" empty object but now my tiles list is returning null.
as in, TileData is null?
No, "tiles" the dictionary i add to at the end of this foreach loop is causing null reference errors when I try to call foreach loops on it later
this is a custom grid not the unity one ?
one thing that jumps out at me: do not use Vector2
floating point errors abound
Vector2Int will be much more reliable.
ah kk
are you sure these are null reference errors and not "item does not exist in dictionary"?
particularly in pathfinding when I go to make all the nodes, I'm getting a NullRefrenceExeption on line 27(the foreach line)
that means you don't have a tiles dictionary at all...
i'm pretty sure it's fine to put null in a dictionary
that wouldn't cause an error in its own right
(or maybe GridManager.Instance is null)
it shouldnt be? i dont even know how it would be. like its attached to an empty in the scene called GridManager if you mean that it might not be on an object
well, go check it!
log those things before you hit line 27
merely having null values would not cause an exception in the foreach line
it also matters when you call these methods
indeed
as anyone who has tried to sit on a chair that just got pulled out from beneath them can attest to
Hi there, i'm having an issue with syncing my Network Variable is this the right place to ask about this?
check #archived-networking
thanks
okay its weird becuase, I put a break point at the bottom of the FormGrid method and the tiles dictionary filled up with tiles correctly... and its still correct once I reach the MakeNodes foreach loop in pathfinding (i put another break point there) but then it throws the error...
it throws the error from the foreach line?
and you are confident that GridManager.Instance is not null and that GridManager.Instance.tiles is not null?
have you proven this to yourself by logging all of these things?
i'd do it even if you think that's the case from the debugger
might as well see exactly what it sees
yes you don't know until you know
wym by logging? just by passing through Debug.Log?
oh yeah i did that
You should be able to see what's null then