#archived-code-advanced
1 messages ¡ Page 195 of 1
Hello! I have question!
I currently have a pinch scale touch control. where when I zoom out the object gets bigger! how can I inverse that
To where I zoom out object gets smaller
Does anybody have some good reading or videos on behavior tree implementations in Unity?
Trying to find something that isn't a 20 minute video explaining just the basics
Posting the code instead of a screenshot of the code is easier to work with.
But I guess transformToScale.localScale = initialScale * (1 - touchDistanceDifference);
DIdn't want to flood it
What piece of code am I looking at now?
This seems like rotational code
protected override void scaleStart()
{
scaleCoroutine = StartCoroutine(scaleDetection());
}
protected override void scaleEnd()
{
StopCoroutine(scaleCoroutine);
}
private IEnumerator scaleDetection()
{
Vector2 currentTouchPrimary = touchControls.Touch.PrimaryFingerPosition.ReadValue<Vector2>();
Vector2 currentTouchSecondary = touchControls.Touch.SecondaryFingerPosition.ReadValue<Vector2>();
float initialDistance = Vector2.Distance(currentTouchPrimary, currentTouchSecondary);
Vector3 initialScale = transformToScale.localScale;
curState = State.SCALETRANSLATE;
while (true)
{
if (curState == State.SCALETRANSLATE)
{
currentTouchPrimary = touchControls.Touch.PrimaryFingerPosition.ReadValue<Vector2>();
currentTouchSecondary = touchControls.Touch.SecondaryFingerPosition.ReadValue<Vector2>();
float currentDistance = Vector2.Distance(currentTouchPrimary, currentTouchSecondary);
//if accidentally touched or pinch movement is very very small
if (Mathf.Approximately(initialDistance, 0))
{
yield return null;
}
var touchDistanceDifference = (currentDistance / initialDistance);
transformToScale.localScale = initialScale * ( 1- touchDistanceDifference);
}
yield return null;
}
}
Yeah does that work?
I would probably do it as
var touchDistanceDifference = (initialDistance / currentDistance);
instead of the 1- approach.
That worked perfectly I cannot believe I didn't think of trying that!
The -1 worked as well it was just a little harsher and on initial press would reset the values but with some finagling it would work im sure
my goodness. that was just 3 hours of struggle when I should've gone here first
Thank you all!!
np
I have a script with a lot of fields for configuration, I am planning on moving these fields in to a struct instead. How can I make sure that values that are already set on prefabs are properly copied in to the new struct?
Write some code that copies the values into the struct, make sure they're copied, delete the old fields.
Question regarding streaming asset bundles (addressables might be relevant too?)
I'm trying to load an existing, published catalog into the editor, create a new asset with a reference to a scriptable object inside that catalog, and save it as a new addressable streaming bundle
Is that possible? I can load something from an existing catalog, and instantiate it, but trying to copy a reference just clears itself, because it's an invalid reference...
what is your objective?
why into the editor?
from your game?
or a different game you dont' have the project for?
you can't mod this way
in the prefab's text form you may be able to move the fields "down" into the struct with something as simple as a tab, provided you name them right
the best way to "make sure" is to use source control and compare
why is this in a coroutine
i guess it's fine this way
you can use += performed instead and it will be simpler and clearer
modding, yea. I can load the game assets into the editor, and my own assets back into the game at runtime.. but no way to reference game assets from my assets
why dont you make modding based on xml or json
in this case, I'm trying to mod a released game that the devs are happy for people to mod, but aren't will to build tools
I ended up using ISerializationCallbackReceiver to copy and it seems to work fine
i need a way to disable the convex collider triangle limit
hey, i'm running into a little issue here. i can't get contact points for within the collider if it's a trigger. i tried looking up some solutions and found one that says giving the sphere a rigidbody and setting isKinematic to true should work, but it still collides with the ball. any idea what to do?
void Start()
{
m_Collider = GetComponent<Collider>();
m_Center = m_Collider.bounds.center;
}
void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
strength = m_Center - contact.point;
Debug.Log(strength);
Debug.Log(strength.magnitude);
}
If my collider is a sphere, strength.magnitude should always be the same, right? the distance from the surface of the sphere to the centre is what it's meant to be modelling, so it shouldn't change. yet, it does. what have i done wrong here?
It's OnTriggerEnter then if the collider is a trigger.
the collider is currently not a trigger, because i couldn't get contact points to work with it as a trigger
Hmm
Well can't help atm, i'm at a party, but that would make it quite hard without a trigger. If it's too far in the sphere it would resolve the collision with extreme force right? The ball would bounce off really hard that way.
you're correct haha, that does tend to occur
I do not understand why OnTriggerEnter would not work, because that also has a OnTriggerEnter(Collision collision)
The collision should also have contact points
if i change it to that, i get this error message
and if i change the first collision to collider, i get this
Ohh damn, I read that wrong then.
thanks for trying to help though, enjoy your party đ
https://answers.unity.com/questions/42933/how-to-find-the-point-of-contact-with-the-function.html is the only thing I found, yeah thanks đ
Is there a way to pass a class as a variable? I.e. var foo = CustomClass; bar = new foo();
I have a class that I need to run new () on but only at a specific time. If I just do var foo = new CustomClass(); it runs on declaration.
What? Do you mean pass a class by value instead of reference?
If so then you want to use a struct instead most likely. The other option is to implement a Copy() method which creates a new instance of the class and manually set the fields of the copy to be the same as the original.
not really. I need a way to declare a class without constructing it. Then pass that declaration to another function which then constructs the class.
I'm running into a stack overflow error.
like CustomClass foo;...?
I have an abstract class Dialog. I extend this Dialog into Foo, Bar, ect. Each of these has a function that will load a specific Dialog when run. If I just do var x = new Bar() it runs new Bar() on declaration. Which contains a reference to new Foo() which then runs.....
I need a way to make Foo and Bar a variable that I can run new() on.
All 'running new()' does is create a new instance of the class.
It sounds like what you might what is a generic method. But it is hard to understand exactly what you are doing.
It also kind of sounds like you might not really understand how C# works and are trying to do things in a sort of backwards way.
This is causing a stack overflow error when I run because it loads dialog NewGame2 which has a reference to NewGame1. I need to run new NewGame2() at a specific time so I want to use it as a variable. responses = new List<RefDialogResponse>() { new RefDialogResponse() { label= "Next", tooltip = "", checks = new List<RefDialogCheck>(), failedCheckTooltip = "", Effects = new List<RefDialogEffect>() { new RefDialogEffect() { contextType = ContextType.Dialog, connectedDialog = new NewGame2(), context = new LoadDialog(), } } }, };
both of those new Class statements need to go away.
Can you show the relevant bits of the constructors too?
there is a lot of datastructures happening here. What specifically do you want to see?
NewGame2 is the same datastructure as this line because they both extend an abstract class.
Whatever is causing the issue. NewGame2 I would guess.
But it sounds like you simply need to move the code in to a Initialize method and your problem is solved. No?
these are classes that store data. public abstract class RDialog { public abstract Guid ID { get; set; } public abstract string content { get; set; } public abstract string dialogHeader { get; set; } public abstract Texture dialogImage { get; set; } public abstract string imageArtist { get; set; } public abstract List<RefDialogResponse> responses { get; set; } }
I need to figure out how to reference them without calling new to be honest.
I'll have a think about it. Thanks for responding.
What...?
Use a different method instead of new. Another consideration is if you want to force a user to do something before getting access to the rest of a type, make a new type
What is your objective?
Gameplay wise?
When the player hits a button it creates a new instance of that specific dialog which gets stored into a static variable. I then have an event that loads the new dialog with a bunch of classes accessing that stored instance.
#đťâcode-beginner you have to get the callback signatures right
Is this supposed to be a dialog that transitions between scenes?
Like itâs gathering data so that you can load a scene with that data later?
Like a choose your level dialog
Or whatever
What is the dialog
sort of. Instead of doing scriptable objects I am using classes. I want to write it all in code.
these Dialogs are acting like a scriptable object. They contain data and are extending an abstract class.
What is the gameplay exactly
For the dialog and maybe one sentence on what the game is
Game loads dialog. Dialog has a bunch of responses. responses populate buttons. player chooses buttons. event chooses response from list by index. runs that response, in this case, loads another dialog class.
Game is text based turn by turn.
I see
When you said dialog I imagined a popup
Are you trying to say a prompt?
A lot of people struggle with âhow do I wait for inputâ
You probably want something like yield return new WaitForAnswerToDialog()
Would that be helpful?
maybe. I'll look it over.
It doesnât exist
Iâm trying to say that conceptually you are building this big cathedral
To basically wait for the user to make a choice or something
It would be really intuitive to wait in a function but you canât
At least not yet
I donât know why you have more than one dialog class or why itâs called dialog
You should just have one class for the UI that is asking what the user wants to do, which sounds like dialog
Unless you meant to write dialogue
I have been handling it by storing all static data in a data class. When the player does something, it triggers an event which acts on that data in the static class.
I.E. I click a button. It opens Data.dialog.responses[i]
So you meant dialogue as in narrative text with choosable story threads?
yes.
Not dialog as in the programming term for popup windows
That ask single questions
Like the save file dialog
Lol
Dialog in the narrative sense. It is the naming convention I chose to reference any data that populated the big window.
Okay well have you looked at Ink
The word for that is dialogue
You gotta use the right names for things
duly noted.
You should use Ink
If you want a UI around ink thereâs Dialogue Manager asset store asset
And you can customize it to pretty much whatever
Have you ever tried Ink?
Maybe you didnât find it because you wrote âdialogâ into the asset store
Jk
The game looks cool
I really like Ink and use it for any narrative content
Because writers can handle it easily
It already looks like a screenplay which is really reassuring
Awesome. Thank you very much.
I have not tried it before but sounds like it would be worth a look.
I like the single keyboard press energy
You should try formatting it for portrait for phones too
Although itâs tough to say if the average phone user reads lol
Some read
Whatâs great about ink is you could publish an ePub and people can just play your game
Like in their kindle
Or from a text message
At least chapter 1
Youâll see it works well with stuff like inventory
Back from the party, did you find a fix?
nope, currently im just trying to fix everything else, but still havent found a way to make the sphere act like a trigger
That is certainly down the road but I had an idea of making a mobile version. Trimming down the ui and making input bigger to make better use of screen real estate.
so far i've managed to make it so the ball just bounces off in the direction of the normal, but i have two issues
- the aforementioned trigger issue
- the calculation i'm using for the ball vector is
rb.velocity = pos * (5 / strength.magnitude) * 7 + Vector3.up * 10
the issue with that, is if i have an if statement beforehand, it only uses the "Vector3.up * 10" part.
if (control.hit == true)
rb.velocity = pos * (5 / strength.magnitude) * 7;
(with control.hit checking if the player has pressed the hit button)
2 Kinematic ones don't bounce off each other without IsTrigger
But I don't know if that interferes with your other setup.
You can also make a shadow ball clone which is invisible with this setup and read the collisions from that.
Don't really understand the calculation problem
i'm not sure what this means; if i set the ball to be kinematic, it just doesn't move (also i dont know what kinematic means in unity's case lol)
isKinematic Controls whether physics affects the rigidbody.
And since you move with the rb.velocity you can't use it. Then the only option I think is the shadow clone.
Or you ditch the sphere altogether and just use the racket and add the bounce off mechanic from there đ
is it better practice to load JSON data in Awake() or Start()?
alright thanks
with the sphere as an actual collider and not a trigger, right now the hit detection is essentially what it would be if i used the racket bounce off mechanic. and while it sort of works, i dont think its very fun to just place yourself where the ball is
Is that really the case?
But its still called "before any of the Update methods"
@real talon if Im reading these docs pages correctly, there shouldnt be that sort of difference between start and awake, both are called before the first frame is rendered https://docs.unity3d.com/Manual/ExecutionOrder.html#BeforeTheFirstFrameUpdate
Yeah, it looks like your right
any idea why the meshcombine example in the docs isnt working
hey @here, can anyone explain this behaviour? I basically have four identical gameobjects, and they each have the same monobehaviour script attached. the script looks like this:
public class GameEvents : MonoBehaviour
{
public static int instanceNumber = 0;
public static GameEvents instance;
public int instanceNo = 0;
public GameEvents(){
print("Creating GameEvent!");
instanceNumber += 1;
instanceNo = instanceNumber;
instance = this;
}
private void Awake(){
Debug.Log($"Running Awake on Gameobject name: {this.gameObject.name}");
Debug.Log($"Instance Number on Awake(): {this.instanceNo}, Gameobject name: {this.gameObject.name}");
}
...
In the script, there is a constructor which iterates a static int so I can see how many instances there are, and on the scripts awake it tells me the name and instance number of the script I am working with. I also have a button on the screen that when pressed, will give me GameEvents.instance.instanceNumber, so I know the instance number of the static instance being stored. The reason why I am asking this is because I had assumed what would happen is that when the game is run, I would get "Creating GameEvent!" in the console four times, before getting the debug.log stuff from the Awake() method** in the order in which the scripts appeared in the project hierarchy**. Instead, what I get is "Creating GameEvent!" once in the console, before the awake debugs.log run, but regardless of the order of where the scripts were placed in the project hierarchy,** it will always run in such a way such that the awake of the fourth instance is run first, before it goes down to the first instance**. Additionally, if I put the monobehaviour scripts in chronological order with the order of the gameobjects in the hierarchy, the instance number of the GameEvents instance object will be 2, but if i put it in reverse order to the hierarchy, it will be 3.
Can anyone explain any of these behaviours?
What are you trying to achieve here?
All 4 gameobject have their own script, with their own static variables, which they all increment on their own script.
I am just trying to see how exactly unity initialises monobehaviours. It is just understanding mainly.
Not sure I understand the last thing you said in the context of what I've written though
Sorry, didn't know if it is customary to do that here. Too used to pinging on my work slack channels đ
Fortunately these are disabled, like the dreaded @everyone
Unity specifically warns against using constructors in Unity objects as there's no guarantees on the order they run or behaviour of them
What I mean is, every game object has their own public int instanceNo = 0; and public static int instanceNumber = 0; and it seems you want create some sort of Singleton out of this or something that would increase all of them. Except in the current way all instanceNo are 1 after your constructor. So this is all really weird.
So yeah, I would explain this as really logical code, every instanceNo is 1, exactly what I would expect after the increase of 1 from 0.
InstanceNumber is static though, and InstanceNo is being set to it when a new instance is being created.
This is all you need to do.
class GameEvent : MonoBehaviour
{
public static InstanceCount {get; private set;}
void Awake()
{
InstanceCount++;
}
void OnDestroy()
{
InstanceCount--;
}
}
The names in retrospect are confusing, sorry about that.
You don't want to use Constructor for classes that inherit from UnityEngine.Object as was already stated.
Yeah, this is probably a friendlier way of doing it, particularly if I wanted specific behaviour to happen when the object is ran or something. I forgot to mention it, but I did use a destructor in the same class to decrement the instanceNumber variable by 1, so the amount of instances should be correct.
destructors are also something to avoid on Unity objects - prefer OnDestroy
public static int InstanceCount { get; private set; } is cool though, did not know this was allowed.
The private set?
{ get; private set; } this whole thing. Need to read up on what that actually does.
Oh that, that is just a property.
I'm back with a new idea and I have no idea if there is a way to do it. So, in order to create and use scriptable objects, we have to create a script and then we create an instance of that script through create asset menu. Hypothetically, say that we don't care about the resulting object being editable in editor. Is there a way to skip the middle man and have a structure to store data that we can write in script and reference without requiring a constructor? I was thinking something like extending an abstract class with a static class but that cannot be done in c#.
like a text file?
Ah okay fair enough. I think moving them to Awake() and OnDestroy seemed to make things behave as I'd expect. I think it would be interesting to figure out what exactly unity is doing that causes the weirdness with constructors but ill leave it for now. Thanks guys!
It has to do with creating the C++ side stuff.
I don't think that would work. I don't want just storing data but storing functions too. Essentially I want a scriptable object I don't have to instance and is static.
So.... just a static class...?
Yep but when constructing it I want it to force a certain data structure like a scriptable object or an abstract class. I.E. I can require a foo variable and a bar function.
Unity does a lot of management under the hood - one of them being that once a constructor is called it has to set serialized data onto the class which will override values, and there's no guarantees on the order in which it does them
Static classes cannot extend abstract classes.
So use a singleton then?
hmmmm. Are static classes all loaded into memory like a singleton? I learned something today if so.
I had been under the impression it would be lazy and load as needed.
they are loaded in the CLR when first used afaik
but then persist until application close
Yeah
interesting
Does anyone have any info on how different data structures are stored in memory?
or rather links to resources that explain how different data structures are stored in memory?
There are a bunch of buildings. Each building has an int id.
To keep them in a 3d array, ids are used.
My problem is how I should define and distinguish between these buildings.
If I define id as a key with enum type, it is more readable. In scripts, they can be used and accessed with enum names instead of raw int values. The drawback of enum is that values have only one level hierarchy. They come one after another.
Another approach is to define unique string in addition to int id as well. Here, the values can be nested like building/office/medical/..
but I have to create another dictionary with string key in addition to main dictionary with int id key to find that asset as fast as possible by unique string name.
Main Dictionary<int,Building> id -> building
Dictionary<string,Building> unique_name -> building
or
Dictionary<string,int> unique_name -> id (map name to id)
What is your opinion?
Totally, I need int id for each building because they are stored as an int value in 3d array and I would like to access their info/definition data using strings/enums in scripts instead of raw int values.
Option 1: enum ids
Building10:
Id: Building10 (10)
//...
Option 2: int ids + string unique name
Building10:
Id: 10
Name: "Building/Building10"
//...
Hey guys!
Im having problems executing a bash script from inside unity editor. When I debug log the output it gives me nothing. What do i do?
Are you mostly going to be accessing this via code alone, or using properties from the inspector. if the latter, then what you could do is implement something like the LayerMask. So it still uses ids, but has a façade of something more usable.
They are scriptableobjects, a list of so assets
Suppose, both, code and from the inspector.
but we know they can be props in the inspector finally.
public class RailRoadBuilder:MonoBehaviour{
[SerializeField] private string _straightRailName;
[SerializeField] private string _curvedRailName;
//...
private void Start(){
var railRoad = _buildingRepository.GetByName(_straightRailName);
//...
}
}
I had a sort of similar issue to solve. What I did was create a simple node tree, with each node having a name and an id.
The tree is stored in an SO that is loaded, and every node is put in to a id > node dictionary.
Then I have a custom struct that stores an id. This way I can use either the name or the id to get a node. And the struct will cache the reference to the node when it is first gotten. This prevents you from having to deal with mistyping strings.
Of course this isn't exactly the same as your situation as I wanted to access the hierarchy (the parent or child nodes)
Then I have a custom struct that stores an id. This way I can use either the name or the id to get a node.
I did not get it
You had created two dictionaries for id and name keys or ?
map id to string?
For the name I traverse the tree from the root.
or none of them. simply search linearly by name O(n)
OK, thanks
I decided to include int id and string unique names for each asset.
Only create one dictionary with id key and asset value because I need to access data by id as fast as possible. (3d array is large)
but to build some stuff by name e.g. a road, it is not required to get data efficiently. If I need, add the second dictionary
To avoid mistyping about string names, I utilize odin inspector, create an enumerable valid string names and custom list for it
i think you'd want to reference these game objects dierctly
as prefabs
there's no cost to referencing a prefab, and you can use the reference as a key
in a dictionary, if you'd like
How would i make another player copy my movements?
controller script listen for the same inputs on both players?
why does the editor eat up more and more CPU over time? Works fine at first and then expands exponentially. Is there a memory leak error in 2021.3.2f1?
I'm assuming your application is running?
runs fine at first then slows down
So there's an extremely high probability that it's something that you're doing with an Editor script.
hm interesting, best guess is something residual from obicloth (although it's not currently implemented anywhere)
Is there a way to give this function a unique id that it will return every time? If I use Guid ID = Guid.NewGuid() it will generate a new guid every time it is called.```
public static Func<RSkill> Skill = () => new RSkill()
{
label = "Aether Manipulation",
description = "You gain a pool of Aether Points which are used to perform Magic skills." +
"\n\n" + "[color=green]" +
"Aether = INT x 5" + "\n" +
"Can equip Magic Foci" + "[/color]",
useType = SkillUseType.Passive,
targetType = SkillTargetType.Self,
tags = new HashSet<SkillTag>()
{
},
cost = new Dictionary<SkillResourceType, float>()
{
},
isBase = true,
isStarting = true,
startingWeapon = null,
unlockedSkills = new List<RSkill>()
{
},
Execute = () =>
{
}
};```
you could have a static dictionary of guids somewhere where you can check against some identifier (perhaps the label or a hash code?) to get/add a guid
if i had it my way though, i would just inherit an abstract class and implement those properties from there and use the class id or something
At the very least it gives me a direction of attack. Thanks.
Just check when its called for the first time and save it to a variable, return the variable otherwise
cached dictionary also works
make own annotation with the id as value
is anyone here able to help me with one of my scripts . It does work but i was wondering if there was a better way to do it cause it seems to run slowly.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@manic stump what are you trying to accomplish with the script? Just placing a bunch of starting items? Cause Instantiation is fairly costly in terms of what can be done in a single frame's time.
And you're creating 1400 things
well im doing a fps game and im trying to place enemy and ammo boxes and medkits in random spots round the scene
Okay.. I wouldn't instantiate them all off the bat. If you want to pregen a bunch of different things. I would create 3 List<Vector3> one for each thing. Then just randomly gen the positions first. Then, when a player approaches and can actually see them, Instantiate it
saves a TON of time
how would i do this im still new to unity
I'd follow some initial unity tutorials tbh. If you're not familiar with the engine yet or OOP in general, do as many as you can. It really helps
what topic would i try to google i have seen so many tutorials i would not know where to start
honeslty, learn.unity.com is decent to get the understanding of the engine.
then just use a codeacademy type reousrce ot learn more oop
does that cost money?
not at all
k ill look into it thx
CodeAcademy costs money for anything past the basics iirc
For some reason my script won't get past the WaitForSeconds. It outputs everything in the debugger before that, but nothing after
{
Debug.Log("We have started the slow down script");
if (!slowDownActive)
{
slowDownActive = true;
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
//Tell enemies to slow down
for (int i = 0; i < enemies.Length; i++)
{
GhostFace enemyScript = enemies[i].GetComponent<GhostFace>();
enemyScript.SlowDownTime();
Debug.Log("Slowing down for ghosties");
}
Debug.Log("Made it to the counter");
yield return new WaitForSeconds(slowDownLength);
Debug.Log("WaitForSeconds completed successfully");
for (int i = 0; i < enemies.Length; i++)
{
GhostFace enemyScript = enemies[i].GetComponent<GhostFace>();
enemyScript.BackToNormalTime();
Debug.Log("Back to normal time");
slowDownActive = false;
}
}
}```
Either slowDownLength is very large, or you destroy the object this script is on
It's pretty short and I made sure that the script won't be destroyed even on reload
//Makes sure the GameManager is kept between scenes. If there isn't one, then create it
DontDestroyOnLoad(gameObject);
if (instance != null && instance != this)
Destroy(this.gameObject);
else
{
instance = this;
}```
Sorry, I should specify, the don't destroy on load runs at start
That looks a lot like destroying the object
Should only destroy it if at start another version exists
Well, the coroutine is destroyed because the object is destroyed. You'll just have to find out why that happens.
That's weird, any idea why it would output
Debug.Log("Made it to the counter");
but then hang on the WaitForSeconds? I don't have StopCoroutine or StopAllCoroutines anywhere in my code, so not sure why it would stop
because the object is destroyed while it's waiting
Sorry, just wanna make sure I understand. Do you mean that because it's waiting it's being destroyed, or that some other script is destroying it while it's waiting?
The coroutine stops because the gameobject that it's attached to is destroyed, for reasons unknown
I'll take a look around and see if I can confirm whether it's being destroyed or staying up. Thanks!
Good morning everyone! Stay hydrated!
AH you're right @devout hare
It wasn't destroying the gameobject with the script, but because the script that started the coroutine died, it was cancelling it. This is the gameobject that was starting the coroutine
{
Debug.Log("Me ghost, me ded");
if (!timeSlowActive)
StartCoroutine(gameManager.SlowDownEnemies());
Destroy(this.gameObject);
}```
Seriously appreciate the help!
Right, the object that starts the coroutine is what's responsible for managing it
so yeah, this is now solved
JsonUtility.FromJson<PlayerConnectionData>(Encoding.ASCII.GetString(connectionData));```
This is where the server takes the connectionData byte[] and converts it to my class which just contains a string called username. Whenever I use username it always has a "?" at the end, so say my username was Test, it would look like: Test? Does anyone know how to fix it?
is there some end of line delineator being added?
I am not sure, its the first time I worked with encoding like this, but just encoding the string and back in the same line does it as well
is the encoding ascii on both ends?
one could be unicode
could try utf8, I think that's compatible between both
I have a List<SimpleClass> myList this classes have
-int soID (not unique)
-boolÂĄ completed
I want to check if there are > 1 item with the same soID and not completed
Im trying to do it by Linq but dont know how to separate them by soID
I'd like something like:
myList.Where(x=> (same soID) && completed==false).Count > 1````
hey guys does anyone know how to call a bash script thru unity
what's your objective?
im trying to create a dotnet console project (VS project) and make the script the automates that process run in unity
you can use GroupBy and check if any of the groups have a count greater than one
for what purpose?
what is the script?
what's the objective? like what does it do
it creates a dotnet project and gets all the files it needs from a sppecific directory and then build it so i could get the .xml documentation in the build
because in unity i cant do that
// this is a list of groups by soID
myList.GroupBy(x => x.soID)
// select out the count
.Select(x => (id: x.soId, Count: x.Count))
// filter by count
.Where(tuple => tuple.Count > 1);
it works in the terminal perfectly i just cant run it in unity
is this on mac?
i am trying to understand what it is you're trying to do
maybe give me the big picture
i'm sure you've googled "how to start a process c#"
so i don't think that's your issue
in general im trying to create an automatted documentation system. its finished but in order to do so i need the xml of a package then i parse thru all the xml comments and create documentation for any unity package. Before this script people had to do like a 10 min process to build the package and get the .xml documentation. So the script runs and does all the for u now but i want to run it in unity because some people dont know the terminal well in my company
there's a lot of work ahead of you for this approach. the fact that your signatures of like Execute aren't async / ienumerator means you haven't yet finished act 1 of this journey đ
yea i did that but the process runs but outputs nothing so im not sure its actually doing it
when you say outputs nothing what do you mean
i don't know what the script is supposed to do yet
my question also which might be the problem is does unity actually execute it in the macos terminal or is it unitys own
ill show u
it's a script that takes a file directory as an input and writes files somewhere?
hmm...
yea it takes the original package directory and the directory u want to output the new project
you authored the bash script?
can you paste the first 3 lines of the script?
i don't need to see the whole thing
it's going to communicate to me how well you know what's going on
cd ${NEW_PROJECT_DIRECTORY}
mkdir ./${PACKAGE_NAME}
cd ./${PACKAGE_NAME}
dotnet new console -n ${PACKAGE_NAME} -o .
okay
thats the beiginning
how many lines is it?
like 30
yea i mean the first lines are variables
#!/bin/sh
#Variables
PACKAGE_NAME=$1
ORIGINAL_PACKAGE_DIRECTORY=$2
NEW_PROJECT_DIRECTORY=$3
okay
so you have a few options
you can (1) try to make this script robust enough to make sense to run from unity
(2) rewrite its behavior in c#
and i was asking the first question cause i had to install dotnet command on terminal so thats why im like do i have to do something for that to work in unity
do i have to do something for that to work in unity
no
hmm
sorry about being imprecise here. robust means that based on the beginning of your script, i can tell you don't know enough about bash scripting or writing these sorts of short utility programs to know how to make them callable from other programs in a general way
rewrite its behavior means you would create a function in c# that does all the things that this script does
you should probably be using Rider instead of VS Code
and you have to install the shellcheck plugin
i see
and i need the shell check package for unity?
oh
so really creating a new process in c# is so straightforward
it's so well documented online
i think what is confusing to you is that the program you need to run is /bin/bash
with the argument that is your script
i made the process tho
followed by the other arguments
but the positions are going to be wrong
surely this was online though
and i did what people say online its just not outputing anything
no error or anything
it's on the first result for me
"how to start a bash script from csharp"
there's a lot here
i don't mean to give you a hard time
but i'm trying ot understand what the actual issue is
you are running into a pitfall regarding the bash argument positions
here's another example
my suggestion is to rewrite the script in c#
it will take you less time than diagnosing this
i don't know what the end goal is though, because if your colleagues can't run a command from terminal
well they're not going to be able to install dotnet, nor the package that you're using to read the doc comments
it sounds like your goal is "produce documentation for people"
it's confusing why though?
why do they need the documentation from here?
no they can install i mean dotnet and my package is a unity package so its fine
someone who can't program or use the terminal, what use are comment documentations
well how do you think they install dotnet?
but i mean i dont want to harcode the commands u know
i mean i only need one person to
but like im just trying to make the process as easy as possible
you can also just commit the files it outputs to source control?
why does there need to be a script at all
i don't know what would consume doxygen output
no i dont want that
because i dont want specific information on git
is it because vs code is not showing inline documentation correctly?
i suppose you could just delete it no?
it doesnt show inline documentation for unity packages
okay. so is this your actual problem?
its not possible so i created the script to do it or else its like 10 min of bs
"vs code does not show inline documentation for unity packages" ?
yea but its not a problem anymore cause the script does it
i'm not trying to give you a hard time
no i know im just trying to explain
so why are you using this absolute dogshit editor?
VS?
yes, vs code
because unity has specific referneces
no yes in rider
ive done it
you can create .xml in rider for a unity package
it wont work without all the refernecs
cant
so i like copy the refernces and put it inthe new dotnet
creating a solo project instead of a package works so thats why i have to go thru all the bs
but i dont need that
i need to just run the bash script
like i have a solution already
i think you should be able to run it using new process
the alternative is i write this bash script for you
or you rewrite the thing the script does in C#
there aren't any tricks to diagnosing this.
your issue right now is the process you should run is /bin/bash, the second argument is the path to the script, the third+ are your regular arguments, and you need to set the working directory correctly
you can redirect standard out somewhere. but then you have to know what that means
you've probably set PATH incorrectly. you can always use an absolute path to the dotnet binary
which is probably another issue
do you see what i mean? all of this is just flaws in trying to do this with a script
also it's not clear what you mean by this function
do you mean the Skill function or Execute
you could always do
public static Guid SkillFactoryGuid = /* declare a guid from a string you write yourself */;
public static Func<(RSkill, Guid)> SkillFactory = () => {
return (() => { ... }, SkillFactoryGuid);
}
i think the user didn't realize he needs to write a guid
he can't call new guid
i think he was having a brain fart
a guid also wasn't used anywhere in his snippet so i have no idea what he means
yes i see what u mean thank you. I have done it with the process command and added the arguments with that with psi.arguments and when i redirect the standardf output theres nothing so im just trying to get a you know error or something. definently cant give u the full script but thanks for offering. i made the psi.filename also "/bin/bash" and gave the actual filename with arguments in the process too. I use absolute paths but can you point me in the direction of how to write the script so it wont be confused. should i delete the variable lines?
also i do appreciate everything sorry if it comes across like im not im just stressed and been stuck on it a while
it's okay
it's just tough because it's not your fault unity doesn't create these files
you sould probably rewrite it in c#
it will be faster to do this
and you'll be more aware of what's going on
hey guys, does anyone know why cocoapods would fail to install on mac?
im mostly a windows user, can't figure it out
system ruby is hard to use if you're not familiar with these quirks
you can't really do sudo gem install cocoapods
is that what you did?
yeah i did that
it's saying that ruby is not in my path
no. sorry, first i try sudo gem install cocoapods
it says i don't have write permission
then i try "gem install cocoapods --user-install"
and it says that [path to bin] is not in my path, executable won't run
iOS resolver in the project fails, so i figured i gotta install this thing in the system first?
@undone coral so thank you i actually got the bash script to run. but my dotnet commands dont run in the script. Is there something i have to do to get dotnet recognized by unity
i think you should punch into google stackoverflow cocoapods install macos
because it's just a bunch of arbitrary stuff
you have to change your script to use the absolute path to the dotnet executable
the issue is that you are using .bashrc or .profile to modify your PATH
you can add the argument -l to /bin/bash to make it load your .profile, but that's not going to work on the other user's computer
does this make sense?
yea it does. so what would be my best option? To tell people to have it in the same place?
everyone should have it in : /usr/local/bin/dotnet? and run it with that
Thanks!
pretty much everyone on macos will be installing it via brew
so it will be there
have anyone seen this error before ?
Missing shader. PostProcessPass render pass will not execute. Check for missing reference in the renderer resources.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
there isn't really enough context to diagnose anything here
thank you @undone coral I did it!! tyty
Is there something about building using Dedicated Server that would cause collisions and triggers to not work on nested colliders?
if the collisions and triggers use mesh colliders maybe
it might strip meshes
Yep. For the GameObjects affected it does use mesh colliders. However, before, when we weren't nesting the colliders, it was working.
is there a way to debug every float in your script via algorithm, instead of specifying every single float individually?
with reflection you could I guess - or serialize your class to json (which uses reflection usually)
i think you'll have to file a bug
i wouldn't recommend using the dedicated server checkmark
It's no different than launching the application in batchmode.
im getting an issue with microsoft visual studio: whenever I open an error from the console to bring me to where the error is, even if the script in question is already open, MVS reloads the whole project, and its really slowing things down
from looking at what it does in the bottom left, it apperently unloads, then reloads the project for some reason?
Is the ide set up properly?
it seems like it is, how can i know for sure?
Take a screen of the whole ide window with any unity script open.
sorry, it didnt get the bottom part
The important part is that the assembly shows up properly ("assemply-csharp"). That means that it is configured properly.
you mean this part?
That too, but mainly the top-left part that shows what assembly the script belongs too.
Can you take a screenshot of your unity editor - preferences - extarnal tools tab as well?
Does that vs version correspond to what you're actually using?
Try unchecking all the tickboxes and regenerating project files as well.
yes, and yeah let me try that
that seems like its fixed it, but ill let you know if it happens again.
Thanks dilch
Obviously it isnt actual syntax but you get what i mean right?
https://www.gamedeveloper.com/programming/c-memory-management-for-unity-developers-part-1-of-3-
These articles are almost 9 years old now.. but it's an interesting take - that unity's memory management sucks. I don't have enough experience to know. Anyone have experience dating back to 2013 that has an opinion on this?
didnt look too in-depth, but this article seems to look more at .net's lack of manual memory management and ways to work around it rather than memory problems within unity itself
Gotcha. I also noted they make a lot of references to Mono which .. as far as I understand .. is arms-length from Unity, no? (I'm using IL2CPP anyway fwiw)
mono is just a .net implementation that unity just happens to use. it does talk a bit about how mono's gc is a bit lacking speed-wise which does unity still use, but i wouldnt consider that to be unity's fault but rather mono's
Hello guys, i have this complicated issues with Vs and unity at the same time, Its hard to explain so id like to vc with someone later today, anyone wanne help?
If your comfy with vc ofcourse.
Hi, how come sharedMesh.vertices.length is different from sharedMesh.vertexCount?
That is the mesh
Oh, is it because of Read/Write
Yes, it's because of Read/Write, nevermind
hello guys can anyone tell me how to shoot gameObjects(bullets) from my gun in unity, and btw not using raycasting only the gameobjects collider
Instantiate them at a point (Or pool because we're in #archived-code-advanced) then give them a force?
I have heard about instantiate but wtf does it mean?
Coming from the Latin Instantia it means "represent as or by an instance". Which in Unity terms just means it creates an object
umm ok
We're in #archived-code-advanced I would expect you to know about Instantiate really, and at least Google it yourself
ok btw I found a tutorial in youtube let me learn(copy code coz it has a link) from the video
its not working, i gotta learn about instantiate
where should I add my rb force btw?
is this the right place to get code help about navmeshes
perhaps, probably depends on your question.. use your best judgement đ the answers you get here might be a lot more high level, where you're expected to know how to do something at a nuts and bolts level
if you're going to ask what Instantiate() does you might have a bad time
no it not that i know how to do that
probably just go ahead and ask then and if it's the wrong place, someone will (gently or not) tell you where to go đ
i just having problems where i use a raycast to find the navmesh so i can try to spawn an enemy prefab on it but it does not work properly
should i show the whole code or just where is goes wrong
both, probably - discord is good for 5ish lines of code at most, if you think you need to show more, use pastebin.com
and also don't repeat characters in your messages or the bot will auto delete it đ like you probably just found out
https://www.toptal.com/developers/hastebin/zolujiruco.csharp
here the part i seem to do wrong
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it spawns them ok but how would i have it check what the raycast hit before it puts them in the scene if it hits the ground not a tree etc
so probably more of a question for #archived-code-general or #đťâcode-beginner , but if you check into the API docs, the raycast method has properties that you can enumerate through to see what's been hit.. i think the collection is literally called collisions
(this is the type of answer you'll get here - "use the collsions collection returned in the Raycast() call", whereas the answer in general or beginner is much more likely to contain actual lines of source code you can copy or modify)
ok ty
also .. just in general, your block of code is confusing because of your lines 4/5 - if you don't use braces with if statements, then indent the next line or put it on the same line, because it's not obvious at a glance that line 5 is in the if statement
and maybe that's a bug
// do this
if (thing == thing)
{
DoThing();
}
DoNextThing();
// or this
if (thing == thing) DoThing();
DoNextThing();
// or this
if (thing == thing)
DoThing();
DoNextThing()
// don't do this
if (thing == thing)
DoThing(); // <-- bad
DoNextThing();
ty again
Is there a way to have a component run a method when a scene is loaded in Edit mode?
I have a script that updates some things when scenes are loaded or unloaded additively. It'd be useful to be able to see those changes in Editor when the scenes are loaded, rather than having to go back to that script and click a button to trigger the script
example from my codebase:
#if UNITY_EDITOR
private void OnValidate()
{
UnityEditor.EditorApplication.delayCall += OnValidateCallback;
}
private void OnValidateCallback()
{
if (this == null)
{
UnityEditor.EditorApplication.delayCall -= OnValidateCallback;
return; // MissingRefException if managed in the editor - uses the overloaded Unity == operator.
}
InitializeComponents();
DoLayout();
}
#endif
I use the delayCall .. because.. I can't remember the exact reason but there's some unity oddity where it starts spamming you with error messages if it tries to do stuff in the same tick - you have to do it a frame later (in the editor)
this will also run anytime the gameobject it's attached to is modified, so .. if you start moving the actual game object around your scene you're gonna get a lot of these calls
I do something similar with EditorApplication.heirarchyChanged, but it's not working
Got a problem wih unity test framework. I have multiple tests that basically start the whole game from scratch using [UnitySetUp] and clean up scenes using [UnityTearDown]. These tests work when runned separately, but they fail randomly when called with "Run All". There are MissingRefExceptions everywhere and it happens at random. What i might be doing wrong? it seems unity doesnt clear all objects or keeps invalid refs in between tests đ
are you using the delaycall pub/sub model?
like doing it a frame later
There's a lot of weird issues with MissingRefExceptions and unity due to the sort of wobbly way it tracks objects (ie, .meta files). I don't know how it works under the hood for setup and teardown, though.. you might be better off talking to unity directly if you have the support license
I have:
#if UNITY_EDITOR
void OnHierarchyChanged() => UnityEditor.EditorApplication.hierarchyChanged += OnHierarchyChangedCallback;
void OnHierarchyChangedCallback() => UpdateSceneItems();
#endif
yeah so I'd use delaycall
(instead of hierarchychanged)
i've never tested order of operations (or even used hierarchychanged) but it might be getting called before your hierarchy is fully loaded, so if your script is fiddling with other things that are supposed to be in the scene, it might not find them?
delaycall runs at the end of an update tick
I've changed it to delaycall, but it still isn't running
put it in OnValidate
oh
check to make sure this isn't null and if it is, delete the callback and abort
void OnValidate() => UnityEditor.EditorApplication.delayCall += OnDelayCallback;
void OnDelayCallback()
{
if (this == null)
{
UnityEditor.EditorApplication.delayCall -= OnDelayCallback;
return;
}
.. do init here ..
}
Ah! I was being dumb. The first part needed to be the class name. I'm a dummy
Thanks @misty glade
imma need to use the legacy ui is it gonna be removed shortly?
by legacy you mean ugui or the legacy text (not text mesh pro)?
most likely neither will be removed in few next years
is it possible to use "exist", or "for-all quantifiers" in c#/c++?
yes
i assume there are reserved keywords like "for" for the quantifiers? siince theres no shortcut. i cant find any infos on that. like foreach and except? but you cant use foreach in constructor
there's core language features like foreach and a lot of extra query tools for enumerables in the System.Linq namespace
what are you trying to do?
the canvas one
before the ui toolkit
cause the ui toolkit input is not very customizable
i just want to understand semaphores (university topic: computer science) and i need to write an example in code. allright, so i guess i would need to use linq. thanks Deynai! but anyway this is c:if (âi: so->s[i]==true & âj: so->wt[j] != EMPTY) { âi: so->s[i] = false; âj: deblock(so->wt[j]) }
Ah, thats going to last many years I believe. Only very recently they added even possibility to use the ui toolkit for runtime uis and the ui toolkit is far from ready, they are still adding ton of festures to it. The âoldâ ui system being legacy means unity is most likely not going to add many new features to it anymore (which they havent done earlier either afaik. Other than tmpro being added, i dont remember any features they have added in the past few years. correct me if im wrong, most likely i have missed something obvious). Also if youre not going to upgrade to newer unity version during the project, you dont need to worry because unity will not remove it from existing versions but instead not support it by default in the future versions (will take few years i think). Even then you could most likely use the old ui by installing the package and maybe do some extra set upping. So id use the legacy ui, no need to worry at this point
for the predicates: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all?view=net-6.0
and for/foreach for the iterator
I imagine not the route you want to take for learning about semaphores though
Has anyone else noticed that task cancellation (async/await) has become asynchronous somewhere between 2021.0 and 2021.3? At least in some situations, if you await on a task that will be canceled, the cancellation doesn't process synchronously, but instead later in the same frame. I reported this as a bug over a month ago, but haven't yet gotten a response. Wondering if it's actually a bug or intentional for some reason.
Wouldn't that just depend on when you're handling the cancellation? ie - if you're doing any sort of task management in Update() you aren't guaranteed that other updates of game objects are before/after this one, so they might appear in the next frame
I would assume the await to return immediately when I call Cancel() on a CancellationTokenSource, but it doesn't. This is different from standard .NET and earlier Unity versions.
...when everything is happening on the main thread, that is.
which .NET? I know cancellation tokens and behaviour changed in .net6
i don't recall exactly what, though, i don't really cancel my tasks đ
did you unsub from the event in the handler?
đ
the if this == null part
this is the script I have: https://pastebin.com/kxsMgfNA
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hmm, that's actually a good point. I'm using netstandard2.0 (to more easily stay compatible with Unity), let me try with newer .NET. I also tried on sharplab.io, though, which I assume is using the latest.
EDIT: No actually, the test project is .NET 6, the library I'm testing is netstandard2.0
yup, you have to unsubcribe from the event, your older instances are still subscribed to it but don't exist anymore
ok...going to try it
Change to:
#if UNITY_EDITOR
PersistenceManager() => EditorApplication.hierarchyChanged += OnHierarchyChangedCallback;
void OnHierarchyChangedCallback()
{
if (this == null)
{
EditorApplication.hierarchyChanged -= OnHierarchyChangedCallback;
return;
}
UpdateSceneItems();
}
#endif
also strongly suggest (as before) that you use .delayCall instead of .hierarchyChanged because you'll get some hard-to-figure-out bugs if the hierarchy is incomplete (i believe)
@misty glade seems to be the same on at least netcoreapp3.1, .NET 6 and older Unity versions, just different on 2021.
ok so .. await doesn't break as soon as a task is canceled (weird, right?) - so I think what you need to do is literally create the task from the call, create a cancellation token, and then try/catch yourTask.Wait(yourCancellationToken);
CancellationToken cancelToken = new CancellationTokenSource().Token;
Task t = Task.Run( () => { YourMethodAsync(); });
try
{
t.Wait(cancelToken);
}
catch (OperationCanceledException)
{
...
}
or something, I dunno, maybe that's butchered
I am having a serious issue: Unity keeps changing the capitalization of a script name. When this happens, it breaks the connection with Inspector. I have to go through and rename this file every single time I start Unity.
Thanks, but I'm not really looking for a solution, rather to understand if this might be an intentional change in the Unity synchronization context. In my use case everything is running on the main thread, so using Wait would deadlock.
Yeah, this is a part of unity that sort of sucks. In general, never edit files (filename, directory, etc) outside of unity (in the OS or visual studio).
What I'd do is copy the content out of your script to another file, then delete the script (in unity), recreate it (with the proper capitalization) and copy the content back into it.. It's going to break all your prefabs/gameobjects that use the script, FWIW, so ... you know, maybe don't do that if that's going to be a massive nightmare to fix
I don't have that option, this script is one of the major components of the game.
i think alternatively you can rename it in unity and it should fix it.. but yeah, never edit the files outside of unity, shit breaks that way
Renaming it in unity fixes it until I restart unity, then Unity puts it back
try renaming it in unity and then rebuilding the asset library.. i don't think the meta files have the name of the script in them but I don't know where else that might be embedded
assets/Reimport All
it'll give you a scary sounding dialog then chug away for a few minutes
i learn at university, i just want to understand the syntax my profs use. its not linq they use pseudocode to directly use the quantifiers. someone told me that its possible to use your own keywords/shortcuts for predefined functions like â. since i type it here i can use it as a string and to create something like if (âi: so->s[i]==true & âj: [...]
if you write your own compiler maybe - you can take some shortcuts with aliases but changing the structure of the syntax is another issue
yea thats the topic: compiler^^. but i just wanted to understand the basics here. thank you bro!
Code snippets can turn some characters into fully-fledged pieces of code
But from what I understand, this means "if all elements of the set are true and [something else]", which can be achieved with LINQ
if (els.All(e => e) && ...), where els is any collection of bool values
yap
https://en.wikipedia.org/wiki/Typedef found it. but its not c# though
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. As such, it is often used to simpli...
Oh we can do that in C#, where the using statements are.
using MyDebug = UnityEngine.Debug;
It makes an alias for the type
it also doesn't do what you described you wanted it to đ¤ˇââď¸
i have no idea what this is
looks like lambda calculus
but it's not
you can't use bog standard c# async in unity robustly. use unitask
? what is its name
it's pseudocode with a mix of mathematical symbols and C/C++ where âi: means "for all i such that", that translates effectively to what SPR2 said: if (so.s.All(e => e) && ...)
what's your objective?
not mine - I've been wondering the same thing about the original question
a semaphore example
ah
that's right
that's what @crystal wasp wanted, a semaphore example?
no i just wanted to understand the syntax my profs use. its not explained anywhere in their papers
you'd have to share the class
they created an alias for an array/int-function with typedev to use â. i just wanted to know if thats possible. but anyway the question is not related to c#
Wrote this today because @kindred tusk made me. Feedback solicited! https://github.com/cdanek/kaimira-weighted-list
did you look at the apache commons implementation
...... I didn't know there was one? đ
have to run to kids soccer but link me, i'll check it out when i return
Only skimmed it, but I think this is different? Mines weighted and has functionality to draw items randomly by weight.
This looks very useful
did not
It was fun
Thanks for the suggestion, but my use case is pretty far from typical: it's a testing library that also works with .NET. I want to avoid adding a dependency to UniTask, and want to keep using standard .NET tools during development, which are not available for Unity (like running tests & coverage automatically in Rider on every save, stryker.net mutation testing). Also, due to its nature, avoiding allocations is not really a top priority.
Also, given https://blog.unity.com/technology/unity-and-net-whats-next I would assume Unity would be interested in keeping the basic async/await functionality close to what it is on other platforms.
i am using netfish network and when the player spawn how do i spawn it on the exact position
so far it is not appearing
Could anyone explain to me how the AR Plane (AR Foundation) can be changed into a more "clean" (or project specific) visualisation? The default unity plane isn't that visually pleasing, but I can't find out how to change it (or more specifically what to change it to...)
https://docs.unity3d.com/ScriptReference/SkinnedMeshRenderer-bones.html Is there really no noalloc version of this?
What's the standard way that I should use to get Span from List?
In unity
I have imported System.Memory
Using range syntax is usually how you get spans
??
Range syntax only gives spans if you use it on spans
On arrays it gives arrays
On lists afaik it's not usable at all
you do .AsSpan() and then use range syntax
That's for arrays, not lists
There's no AsSpan for lists
There's only https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.collectionsmarshal.asspan?view=net-5.0 for .net5
Apart from that, reflection hacks
That's your answer đ
Is there really no way to do it normally?
No https://github.com/dotnet/runtime/issues/21727 because lists aren't immutable and can be entirely reallocated while you have a span they don't have APIs for doing it apart from the ones in .NET5 that are unsafe
UNSAFE YOU SAY? https://dotnetfiddle.net/kLEfCX
Is this faster than GetValue?
Also, shouldn't you cache that?
I mean, it won't work with IL2CPP, but yes, once it's compiled it should be fasterâand it is cached
Never used that lambda stuff
public static class ListExtensions
{
private class Info<T>
{
public static readonly FieldInfo ItemsField = typeof(List<T>).GetField("_items", BindingFlags.Instance | BindingFlags.NonPublic);
}
// NOTE:
// One must not add or remove the elements from the list.
// There might be problems with GC if you do.
public static Span<T> AsTemporarySpan<T>(this List<T> list)
{
Assert.IsNotNull(list);
var items = Info<T>.ItemsField.GetValue(list);
Assert.IsNotNull(items);
return (T[]) items;
}
I just did this for now
I'm trying to add a simple culling system to my game where I have trigger volumes that contain a list of objects they should hide when the player is inside them, and I was wondering how best to implement this.
Specifically, I have a house with various rooms, and all the objects in each room are contained within a parent object for that room, so I can hide or show them all by showing or hiding the parent object.
I could give each trigger two lists of objects, one to reveal and one to hide, and then have whichever trigger the player is inside of (assuming the player is defined by a point rather than their capsule which could span multiple volumes) show and hide every object in the list as necessary, but it seems a little absurd to have to list the objects I want to be visible, if that's their default state. I suppose it wouldn't be too much work to do this for my small house and a dozen volumes, but I was wondering if perhaps there was a better way... I suppose I could have one master list of objects in a controller which shows them all each frame before the other scripts hide them, though I'm not 100% certain that scripts will execute in the order I expect them to, which I guess would be the first scene, the first parent, the first child of that parent, and down the list recursively like that? Another thing I could do is have that object have a master list but have the volume read from it and show them itself and since it would be the only one executing since the player position could only be inside one volume, there would be no potential conflicts there. But that feels messier than it needs to be. I'd prefer to keep the objects accessing only their own data as much as possible.
Anyway, just looking for suggestions I guess for any methods I haven't thought of.
Oh, and I already tried Unity's built in culling system. It's awful. Barely culled anything no matter what settings I gave it. So that's why I decided to go this route. The game isn't very large so setting it up manually isn't that big a deal.
Hm... On further investigation it appears you can't count on Unity executing scripts on your objects in any particular order. The order in the hierarchy does not guarantee execution order. It's possible to set particular scripts to run in a particular order in the project settings but that sets a global priority for all scripts of that type. Though in this case I suppose it could be used to make a main script that unhides all objects in a list run before the ones that hide objects. Still, this seems like a bad way of going about it. Perhaps a better way would be to have one script that checks to see if the player is inside various volumes and then grab their list of objects to hide if the player is inside them and then have it hide the objects itself. Or I suppose it could call a method on the volume and tell it to hide its own list of objects. That might be better. This as opposed to having the individual volumes looking for whether a player has entered them and acting on their own.
I'm a bit confused about why script execution order matters between scripts of the same type here, going through all items and showing them only to hide them again seems very inefficient - why not have a state for each volume that gets toggled on entering/exiting?
why not have the objects just hide/unhide themselves? each object would have a list of rooms to show/hide in, and then based on what room you're in, the objects handle themselves
public enum RoomType
{
Kitchen,
LivingRoom,
Bedroom
}
public class InventoryItem : MonoBehaviour
{
public List<RoomType> ShowInRoomws;
public UpdateObject(RoomType currentRoom) => gameObject.SetActive(ShowInRooms.Contains(currentRoom));
}
@silver schooner
put a script on your parent gameobjects (e.g. Room) and have a second script called RoomCuller with a List<Room> with all the rooms in it. RoomCuller has a method public void ShowRoom(Room room) which goes through the list and does ForEach r.gameObject.SetActive(r == room)
volume calls that method on RoomCuller with a specific room.
Or Room has a reference to RoomCuller and calls it with itself as the argument
that article calls out unitask specifically as something they're going to adopt
it depends on your experience level. as you become more knowledgable about async await, you'll see that UniTask doesn't change much at all for the end user of a .net c# library.
Mmm... That feels like it would be less optimal. Every single object out of a couple hundred in the world would have need to have that additional component and be running a script constantly. In a small world with one house that might not matter much for performance, but its also more complex than it needs to be. And in a large open world, that method is definitely not optimal. You'd want some kinda system that group culls objects in that case. Which is kinda what I'm doing here with each room being a container for the objects that are all culled at once.
the allocations story isn't essential. also as your experience level grows, you'll be able to read docs like those and understand that for a certain end user at a certain experience level, allocations is an important story for the purposes of adopting libraries into unity. but at a higher experience level, you can ignore notes like that because they're not meant for you.
you don't have to check it in Update for every object
you could either
A) have a room publish an event that inventory items subscribe to (traditional events or UnityEvent)
B) have your .. game manager, player, whatever, detect when it's in a new room and iterate through all the currently held inventory objects and update their rooms, or whatever
want to keep using standard .NET tools during development
overall this is a lost cause. many developers have wasted colossal amounts of time on trying to make unity look like the .net ecosystem. personally it is low ROI to me.
basically you don't want to do much in Update() - especially for "state" changing things that only happen every few seconds to minutes, depending on your gameplay
i know unity says it will adopt .net 6 AOT, but that isn't going to happen
the company says a lot of stuff
I was mostly referring to the notes about being more compatible with standard .NET libraries and NuGet. I see two parallel stories here: one is the high-performance optimization stuff for where perf matters, the other is integrating better with the ecosystem.
hmm... well out of the box async await on unity is flawed
it's not a performance issue
FWIW just to add to this - ARM64 (as far as I know) doesn't support mono and IL2CPP doesn't support AOT, unless that's what you meant unity said they'd do (add AOT to IL2CPP)
my understanding is that unity wrote it plans to migrate to microsoft's AOT solution
it's possible they have already backtracked and removed that plan
đ¤ˇââď¸ could be - i'm pretty out of the loop with official unity comms channels.. there's just so much bleeping info
you can use packages from nuget in unity, but you can't really use the tooling
again, this is just my opinion, but the value of the tooling is pretty low. i don't save much time being able to add and remove packages to a file
drp: did you see my comments yesterday re: the java abstractbagmap thingy you linked me? my library is for weighted elements in a list
it's okay to sort out the dlls and just drop them in and never think about it again
yes i saw that. i would have to review how i use it in MY card game and i'll get back to you đ
i have some kind of weighted bag random pull implementation
i just haven't looked at it
i did realize on thinking about it further that int for totalweight is probably insufficient.. if you had 1000 items with average weights around 2000, you could overflow
another perspective, and i don't mean this in any way to discourage you from making this project, but what kind of testing in unity actually makes sense?
well i'm stinkin proud of the work I did on it so if you have time, take a look, like and subscribe, blah blah blah đ
O(1) get operations no matter how large the list is
at a high enough level of expanding brain meme, you should see that testing in unity doesn't make sense
it just really depends on your experience level
like you don't need to use the unity editor to test packages. and most of the value of automated testing would be on target devices, like the iphone
but then... do you even use a mac?
do you see what i mean?
so if you're saying no to unitask, well, unitask provides value
it's just something to think about
if you can't see the value in it or getting a testing framework to be compatible with it, you might want to change directions
"code-advanced" perspective
I've been working with Unity since 2015 and did Windows Phone for many years before that. The apps I've been working on are rather menu-heavy, though. This is my testing utility, and it has been very useful for writing high level tests: https://www.beatwaves.net/Responsible/
let's buy you a mac đ
you will really thrive on one
it's time
it's 2022
this looks great
i also think you should try unitask
it resolves a lot of issues
at least study how it's implemented
I have no idea why you're talking about macs, BTW, been working on one since 2015 also...
Nope, Rider.
I had the internals of Responsible written in UniRx, but then I rewrote it in async/await to support standard .NET đ If I was doing this in C++ I could consider typedefing and macroing the heck out of some parts, but i haven't found a nice way of supporting both on C#.
I wanted to confirm something: If I have a Monobehaviour with a Start or Update method, and I derive from that Monobehaviour, can I override the Start method? or do I have to create a new Start entirely?
yeah i see what you mean
You can override (but remember to call the base implementation), if you use new the base class method will not be called.
you could in principle use an include to detect unitask, and do
using TTask<T> = UniTask<T>;
or whatever
you can make it virtual
In every. single. file. đ
I can make Start virtual?!
yes
all Unity does is call a method named Start or something like that so it'll work
you can also make Start a coroutine
kinda cool
Has anyone been able to use roslyn c# scripting in Unity 2021 to run dynamic code at runtime? I've been trying but I get NotImplementedException when I try the simplest C# expression evaluation. No idea how am I going to debug that.
I don't think Unity supports this - for good reason
IL2CPP almost definitely doesn't support it
what's the use case? Mods?
It's a experiment similar to the one that Sebastian Lague did with his coding game.
He used the CSharpCodeProvider which is even less supported I would guess.
Pretty sure I'm failing at the nuget import. Maybe wrong platform or something.
This might be a dumb question but...can you use Expression Body for unity messages? i.e.
private void Start => DoThisThing();
yup, I do it for OnEnable with the new input system in some cases.
Well that's nifty. I'd been avoiding that because I wasn't sure.
It's syntax sugar. It's not an lambda expression.
void A() => B();
``` is just short for ```cs
void A()
{
B();
}
well lambdas are just syntax sugar too đ
đ¤
Good luck with that.
I don't remember details but I've had problems with lambdas that just complicated stuff. It's been a while though.
Pretty sure it was scope stuff.
Yeah, with captured variables it can mess logic up a bit
As it creates a class to hold them, if you change them before you call the lambda, the captured variable will also change
int i = 0;
Action<int> x = () => Debug.Log(i); // capture local i
i++;
x(); // logs 1
I tried building an apk with IL2CPP, but it throws an error because I'm using a Queue?
What is going on, I'm so confused đ
Pastebin: https://pastebin.com/amsRKJTv
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here is my build configuration
Hm.. definitely not the real problem, I built an APK (well, an AAB) with IL2CPP with Queues just a few minutes ago
did you resolve those "script not found" errors i can see peeking out?
are you doing anything funny with reflection? maybe the type is being stripped. Try rebuilding with managed stripping level set to disabled
you can't use any AOT compilers to do this
so you have to use mono to do this, which restricts your platforms to build to obviously too
https://blog.unity.com/technology/1k-update-calls
This web page illuminates how Update methods are called by Messaging System and it says
The thing is that these are the calls from native C++ land to managed C# land, they have a cost.
What is it referring to? As far as I know IL2CPP translates your C# scripts to IL and then to C++ for the targeted platform. In that case everything there should be in C++ without any calls to C#.
he's referring to the cost of putting a method on the stack that does nothing
this is such a silly article, from my very quick read of it
đ
aklsdjf;alskdjf i hate that bot
?
i typed too many dots for a dramatic pause and the bot erased my message
This is a silly article because (dot.dot.dot.dot)..(pause).. he wants to have intellisense show reference counts to unity events?
Obviously if you subclass from monobehaviour and put something in Update() and then inherit from that in everything in your game it's gonna feel bad
The topic is more about how expensive update calls are and how you can replace them
i mean, that's fair, but also.. obvious..?
I think people when they first start with unity do stuff like
public void Update()
{
hitpoints.text = player.hitpoints.ToString();
}
not realizing that's horribly inefficient.. but also at the same time, it's maybe hard for a beginning programmer to understand pub/sub/event models or other ways of doing it
The only thing I am asking about is what are the "C++ to C# calls", if everything is in C++? (I think everything is in C++ because IL2CPP translated all our scripts to C++)
not everything is in C++, only the unity libs are
mscorlib.dll, system.dll are still in the managed world
đ¤
hm actually maybe i'm wrong on that
this is from 2015
Iâd like to point out one of the challenges that we did not take on with IL2CPP, and we could not be happier that we ignored it. We did not attempt to re-write the C# standard library with IL2CPP. When you build a Unity project which uses the IL2CPP scripting backend, all of the C# standard library code in mscorlib.dll, System.dll, etc. is the exact same code used for the Mono scripting backend.
but then there's the whole managed code stripping feature, which.. if i understand, implies that unity actually does crack the hood open on system.dll and mscorlib.dll and strip out managed chunks that aren't called/used to minimize the end build size
the blog article he references seems to indicate that there's a lot of C++ to C# integration: https://blog.unity.com/technology/il2cpp-internals-method-calls
While this is no substitute for actual profiling and measurement, we can get some insight about the overhead of any given method invocation by looking at how the generated C++ code is used for different types of method calls. Specifically, it is clear that we want to avoid calls via run-time delegates and reflection, if at all possible.
interesting
I use runtime delegates allll the time
https://blog.unity.com/technology/an-introduction-to-ilcpp-internals says The other part of the IL2CPP technology is a runtime library to support the virtual machine. but what is THE virtual machine?
I'm assuming the "VM" that runs IL - .net, in this case.. but I don't know (nor really need to know) how it works.. I just call functions, I'm a bad programmer đ
What is the preferred way to edit and store multiple paragraph long text? I am working on a narrative based game and trying to work with json in untenable because json does not support line breaks.
Scriptable Objects
json does support linebreaks btw
so does xml
Thank you.
Is there a better window for editing strings in unity? When I click on it it keeps selecting it all and is a pain to work with.
using something external
I would honestly use a spreadsheet and make a script to import data from it
thats what I did for handling localizations for a game
scriptable objects with string dictionaries that could be imported/created from a xml/google sheets file
How do you work on the text in the spreadsheet cell?
just editing the cell
Alright.
spreadhseet approach seems to be the most common from what I have seen
for localization at least
is there a trick to resizing cells?
I guess I just have to buckle down and figure out how exel works.
we used google sheets, but in any program it's trivial to resize all cells
does anyone familiar with Photon can you give me a overview differences between:
- Realtime
- Fusion
- Quantum
You'd be better off reading their website
How do I find the end coordinates of a rectangular GameObject?
end coordinates?
Let me put it differently, I am trying to calculate what is the closest point of a barrier to my player. But I can't get it right.
{
Vector3 barrier = visibleObject.transform.position - visibleObject.transform.lossyScale;
Vector3 direction = fov.transform.position - barrier;
Handles.DrawLine(fov.transform.position, direction);
}```
On the screenshot the green line represents where the point is right now (which is def not correct)
do you need to calculate closest point to player in any direction or you're filtering to calculate distance from player to barriers only?
I add to the list barrier(s) that is/are in the radius (white circle) in order to calculate closest point from player to the visible barrier(s)
I got a recommendation: You have to instead compute the distance and direction based on the closest point on the barrier. Since they are aligned with the x and z axes, this is quite simple â itâs just the difference in x and z value, respectively, for the two orientations of barriers.
But I still cannot figure out. So, the code is my poor try of implementing this recommendation
So, I managed to get correct direction where the car should bounce (which is perfect), but still can't figure out how to draw a line to the closest point (by which I mean get that point)
{
float x = fov.transform.position.x - visibleObject.transform.position.x;
float z = fov.transform.position.z - visibleObject.transform.position.z;
Vector3 direction = fov.transform.position - new Vector3(x, 0f, z);
Handles.DrawLine(fov.transform.position, new Vector3(x, 0f, z));
}```
Determine which is the closes point then draw the line to it.
Yep, that was the question đ How to determine it
So you ought to break down your problem.. you need to find the closest point first.
Evaluate every object in your collection and determine which is closest.
Actually no, I can figure out myself which one is the closest, what I am trying to implement is a bounce from a visible barrier.
So, when the player comes close to the barrier, I want to push him away from it, but I cannot figure out how to find the closest point of a barrier in order to calculate the direction.
It's a plane
An origin? A radius?
So, send a raycast towards it from your player to determine the closest point.
I understand what you mean, there is also Collider.ClosestPoint. But I am trying to figure out the math way as it is part of the assignment, but my math is not that good
Under certain circumstances, the shortest path would be a raycast from your player in the normal of the plane.
(This wouldn't work if the plane is slanted - up direction is something other than up)
I'm working on a voxel/cube character creator where after building your desired character you can combine the cubes together into one mesh, attach it to a skinned mesh renderer and preview animations on it. The cube prefab is the default cube model just with a custom material. Each cube is attached to one body part (Head, torso right hand etc.) and each body part has exactly one "bone" transform.
https://controlc.com/33bd5870
I'm getting a "bone weights don't match the bones" error. I don't see the reason for the disparity. When debugging the code I confirmed that the bones of the skinned mesh renderer are correctly assigned. All the expected bones, in the expected order.
[SerializeField] private Transform rig; [SerializeField] private Animator animato - 33bd5870
Rig and the body parts for visual reference. Rig visualized by Animation Rigging package
How would i obfuscate JSON data? Right now all my save data is very easily readable and changable
Sounds good
because thats the sense of json and xml ... to be readable
to obfuscate them is senseless... just serialize them as byte code / machine code wahtev er its called
if someone wants to read it ... he will be able to do so
you can just make it harder
Hm alright
if this is for "security" thats just stupid ( dont feel insulted )
obfuscation doenst increase security
Really? How do i stop people from tampering with this stuff then, excluding things like cheat engine
if you want security you have 2 choices.. either Easy anti cheat protection ( client side check if ... not that useful at all ) or server side
server side is the most protective way of securing your game
Why would you care? If someone wants to tamper with their own game, just let them
If it's multiplayer then you shouldn't be saving data on the player's computer anyway
basically it says... "single source of truth" , if a user sends malformed data to the server the server just declines and says " fuck off with that " and you kick him
thats the highest protection you can make... you check every user request
Alright thanks for explaining it
none can change the code of your server
so you know that that one is always unchanged
you will never know what the client will do
decompiled and deobfuscated is done in an hour
thats no protection
its just for annoyance
to be fair, you eliminate a huge part of the cheating with messages that are serialized to byte[] imho
if your data comes over the net in plaintext json .. well, you're pretty much giving away exactly how to modify and tinker with it
path of least resistance - people playing games will follow that even if it means spoiling their own fun. If x mechanic is especially good/rewarding, even if it's less fun, people will do it and then complain that your game sucks. If you have completely transparent and editable save data to the point it's trivially easy to understand and do, people will spoil their own fun by doing it. If you obfuscate it, even just a bit, it can maintain the illusion that playing the game as intended is the path of least resistance and lets them enjoy it as it's meant to be played
Hey!
So I found parts of this code in the internet and am not really understanding it... Any CS and math pros in here who could try to explain what heppens for this 3d cam controller?
void LateUpdate()
{
float scrollData = Input.GetAxis("Mouse ScrollWheel");
targetZoom -= scrollData * zoomMultiplier;
targetZoom = Mathf.Clamp(targetZoom, 4.5f, 30f);
cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetZoom, Time.deltaTime * 10);
currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
currentY = Mathf.Clamp(currentY, YMin, YMax);
Vector3 Direction = new Vector3(0, 0, -cam.orthographicSize);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * Direction * -1;
transform.LookAt(lookAt.position + new Vector3(0, 3, 0));
}
doesn't the tutorial or whatever explain this...?
there was no tutorial
D:
it just sets the orthographic size based on the zoom (mouse scroll) input,
sets the position based on the X/Y mouse movements in a sphere around the target's position
and finally points the camera at a position 3 units above the target
Ok so my orthSize is basically my zoom, makes sense, but why is it getting the Z component of my Direction vector? Does it determine.. like the depth (z-axis)? Because than direction would probably be the wrong variable name for it right? Better name would be "zoom" or so
this part is kinda weird Vector3 Direction = new Vector3(0, 0, -cam.orthographicSize);
I don't see any reason why that needs to be there
it should just be Vector3 Direction = Vector3.back;
also can you explain what a Quaternion (and also why I´m using the Quaternion.Euler) is? Also no worries, I´m currently googling myself, but mayb you have a better explanation! đ
A quaternion is just a variable that represents a rotation
that's all you need to really know
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0); establishes a rotation variable with currentY degrees around the x axis and currentX degrees around the y axis
This part is just saying "put the camera at the target's position + that back vector, rotated by that rotation:
lookAt.position + rotation * Direction * -1;
Oooh, so because im already changing the orthSize of my camera and the only thing i have to do is to negate the value?
no I just don't think this part is related to the orthSize of the camera at all
it should just be Vector3.back * some constant
but they basically have Vector3.back * orthSize
which is pointless, because an orthographic camera doesn't zoom by moving closer/farther from the target.
Honestly my guess is that whoever wrote this adapted it from code that used a perspective camera
and you might be Vector3.back * zoomDistance there in that case
as that would actually make sense for a perspective camera.
You'd put the camera closer/further from the target to zoom
hmm, that seems to work kinda, but no I can zoom all the way
targetZoom = Mathf.Clamp(targetZoom, 4.5f, 30f);
cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetZoom, Time.deltaTime * 10);
```even tho i clamped the value
actually nvm, the value was just to low when doing it like so
any idea tho, why I can´t look further down than this?
because of this:
currentY = Mathf.Clamp(currentY, YMin, YMax);
you'd need to change YMin and YMax to adjust the maximum tilt angle
Awesome, you really helped me out, thanks brother!
actually I do have another question now... I again found this script, which I applied on my player controller, so it moves relative to my cam
float targetAngle = Mathf.Atan2(movementX, movementY) * Mathf.Rad2Deg + cam.eulerAngles;
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
rb.AddForce(moveDir.normalized * speed);
so this variable is kinda weird, bc it always return 57.smth, but without it, my player would always move in the direction in which my cam is looking, no matter the input - at any input for the movement
Hi, i opened my project just now and it compliled with lots of errors. It was fine yesterday when i closed it, but now its messed up. the errors are shown in the image. Anyone know how to fix this?
i have never touched the scripts causing the errors
Are you using the Timeline package?
never added or removed any package named Timeline
Feel free to remove it now
all the errors are from it
think it was from a youtube video
That fixed it man^^ Thanks alot, you saved my ass
is there a way to use Matrix4x4 * Vector4 without removing the w coordinate from the vector?
always strange to see Lerp used in this way, just the arbitrary "Time.deltaTime * 10" thrown in there
yeah I found a way to delete it all the way out and only work with the zoom
looks way cleaner now
There's any way to deserialize XML files to C# classes without manually looping all the XML nodes?
Something like the way we deserialize JSONs?
haha I haven't done that with XML, although it can be more granular. I'd assume you could using the same technique JSON does with custom Attributes
But why would you choose to use XML in this day and age?
Thanks! not my choice actually đĽ˛
How do I set a temporary render texture to randomreadwrite enabled if I cant set that property after its gotten?
are you trying to say you created a temporary render texture
and you have to change this setting
you want to keep the same C# reference, but create a new render texture?
which is routine and possible
i'm not sure about this specific property, it surely can be set by the constructor right?
in unity, the C# object called RenderTexture also holds a native pointer (get native texture pointer)
I use this to create a temporary render texure of a given size I need for this iteration:
RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
if I try to sset it to readwriteenabled it yells at me that I cant do that to an already created rendertexture, but only if I use releasetemporary instead of release to dispose of it
create and dispose / destroy work on that pointer
yeah
the native object that the RenderTexture class manages, which is a graphics device specific thing, is indeed immutable
what's wrong with using release temporary?
it yells this at me
where this is what its yelling at me for
for(int i = 0; i < 5; i++) {
TargetWidth *= 2;
TargetHeight *= 2;
TempTex = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
TempTex.enableRandomWrite = true;
RenderTexture.ReleaseTemporary(TempTex);
}
are you confident you can't enable random write in the constructor?
these are the ways to create it
if not, you have to do
TempTex = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
RenderTexture.ReleaseTemporary(TempTex);
TempTex.enableRandomWrite = true;
RenderTexture.Create /*or whatever it is, temporary*/
well there it is
rendertexturereadwrite
ReadWrite is always enabled by default when you create a texture in memory, at leeast I thought so
readwrite is only for linear vs nonlinear color
you got this
https://docs.unity3d.com/ScriptReference/Texture-isReadable.html
By default, this is true when you create a texture from a script.
why are you setting this flag then
but I need to write to it in a compute shader
i see
so unity wouldnt yell at me
I think you can always write to it in a compute shader. The isReadable flag is about whether there's a CPU-side copy of the texture available or not
this was all to get around the unity object ID being out of range after awhile D:
hmmmm ok
If I remove the enablereadwrite unity yells at me that
Compute shader (Bloom): Property (OutputTex) at kernel index (0): Attempting to bind texture as UAV but the texture wasn't created with the UAV usage flag set!
wait sorry its enableRandomWrite not readwrite
Hey, has anyone tried rendering a USD stage in Unity. I am curious if can use USD's Python or C++ API in Unity to manipulate the USD stage.
what's your objective
USD files have all plain materials with a preview texture
you probably haven't discovered what usd's purpose is
I have a USD stage for a simulation and I want to render it in Unity without converting it to Unity GameObjects
you keep saying stage
what do you mean by stage?
are you trying to say a USD file
what is it really?
for a simulation of what? are you trying to say like a robotics / scientific / non gameplay simulation?
when you say use USD's API to manipulate the "stage," what do you mean?
USD is meant for multiple editing systems to add their own dedicated layers
and to provide some sort of preview / compatibility of those other layers
Ok, so a USD file can be composed of a bunch of other USD files using USD's composition Arc. The final output of the composition is the resultant stage in USD which consists of USD prims.
Unity doesn't know how to interpret layers from other tools in a special way. it only uses their preview features, which is the standard
so you'll see geometry with materials that have a preview texture
Does unity convert the USD to Unity gameobjects to render them?
so what do you mean by that
everything that can be dragged and dropped into the scene is a game object
do you mean does it represent the hierarchy preview as a hierarchy of game objects? i think it does, but i think it's also controllable with a check box in the importer
it "converts" it in the same way it "converts" an FBX to a prefab
the represented hierarchy is linked to the file