textrange losing textpointer reference? - wpf

I've been using some code I found here, to try and change the case of text in a flow document. It changes the text properly however all the formatting is lost (bold, italics, etc) and when I save the document to a XML file all the text ends up in the first Run of the document and all the other Run's are empty.
private void ChangeCase()
{
TextPointer start = mergedDocument.ContentStart;
TextPointer end = mergedDocument.ContentEnd;
List<TextRange> textToChange = SplitToTextRanges(start, end);
ChangeCaseToAllRanges(textToChange);
}
private List<TextRange> SplitToTextRanges(TextPointer start, TextPointer end)
{
List<TextRange> textToChange = new List<TextRange>();
var previousPointer = start;
for (var pointer = start; (pointer != null && pointer.CompareTo(end) <= 0); pointer = pointer.GetPositionAtOffset(1, LogicalDirection.Forward))
{
var contextAfter = pointer.GetPointerContext(LogicalDirection.Forward);
var contextBefore = pointer.GetPointerContext(LogicalDirection.Backward);
if (contextBefore != TextPointerContext.Text && contextAfter == TextPointerContext.Text)
{
previousPointer = pointer;
}
if (contextBefore == TextPointerContext.Text && contextAfter != TextPointerContext.Text && previousPointer != pointer)
{
textToChange.Add(new TextRange(previousPointer, pointer));
previousPointer = null;
}
}
textToChange.Add(new TextRange(previousPointer ?? end, end));
return textToChange;
}
private void ChangeCaseToAllRanges(List<TextRange> textToChange)
{
Func<string, string> caseChanger;
ComboBoxItem cbi = cb_Case.SelectedItem as ComboBoxItem;
var textInfo = CultureInfo.CurrentUICulture.TextInfo;
if (cbi == null || (string)cbi.Tag == "none")
{
return;
}
else if((string)cbi.Tag == "title")
{
caseChanger = (text) => textInfo.ToTitleCase(text);
}
else if ((string)cbi.Tag == "upper")
{
caseChanger = (text) => textInfo.ToUpper(text);
}
else if ((string)cbi.Tag == "lower")
{
caseChanger = (text) => textInfo.ToLower(text);
}
else
return;
foreach (var range in textToChange)
{
if (!range.IsEmpty && !string.IsNullOrWhiteSpace(range.Text))
{
System.Diagnostics.Debug.WriteLine("Casing: " + range.Text);
System.Diagnostics.Debug.WriteLine("\tat: " +
range.Start.GetOffsetToPosition(mergedDocument.ContentStart) +
" ," +
range.End.GetOffsetToPosition(mergedDocument.ContentStart));
range.Text = caseChanger(range.Text);
}
}
}
I can't see any reason why this code isn't working properly. It looks like the textpointers in the textrange object are being redirected to the beginning of the document.

When setting TextRange.Text, it first deletes the selection by telling the TextContainer (the FlowDocument) to delete that content. If that content happened to be an entire Inline with your styling dependency properties then goodbye! So, not only does it get unstyled text, but it sets it
Since you want to keep your existing inline objects you can iterate through the entire FlowDocument to find them and set their text property.
Here is a helper method that only supports Paragraphs and finds all inlines in the entire selection (this logic is a lot simpler if you are always doing Document.ContentStart and Document.ContentEnd). You can expand this to include the inlines inside of Lists, ListItems, and Hyperlinks if you need to (by following a similar pattern).
You should then be able to set the Text property on each of these inlines.
List<Inline> GetInlines(TextRange selection)
{
var inlines = new List<Inline>();
foreach (var block in Document.Blocks.Where(x => selection.Start.CompareTo(x.ContentEnd) < 0 && selection.End.CompareTo(x.ContentStart) > 0))
{
var paragraph = block as Paragraph;
if (paragraph != null)
{
inlines.AddRange(paragraph.Inlines.Where(x => selection.Start.CompareTo(x.ContentEnd) < 0 && selection.End.CompareTo(x.ContentStart) > 0));
}
}
return inlines;
Edit: You will want to cast these to Run or Span to access the text property. You can even just remove Inline and get these types (probably just Run).

Related

Using ANTLR 4 to parse TSQL Joins in Views, Stored Procedures and Functions

Looking for some validation on the approach to using ANTLR 4 to parse SQL joins.
I have generated a lexer, parser and visitor from the following grammar.
https://github.com/antlr/grammars-v4/tree/master/tsql
I can then create a parse tree (in this example for a view) and I can kick off a walk of tree using a listener I have implemented.
ICharStream stream = CharStreams.fromstring(view);
ITokenSource lexer = new TSqlLexer(stream);
ITokenStream tokens = new CommonTokenStream(lexer);
TSqlParser parser = new TSqlParser(tokens);
parser.BuildParseTree = true;
IParseTree tree = parser.create_view();
TSqlListener listener = new TSqlListener();
ParseTreeWalker.Default.Walk(listener, tree);
My question is. Is my method of extracting the tokens for the joins the 'correct' and most efficient way of doing this.
My implementation is below and i based on listening for a walk of the tree at the join conditions. I need to capture table aliases and relate them to columns so I need to be in the same context when I'm walking the tree. Hence I'm manually descending in a single method.
public void EnterTable_sources([NotNull] TSqlParser.Table_sourcesContext context)
{
var table_sources = context.table_source().ToList();
foreach (var table_source in table_sources)
{
var item = table_source.table_source_item_joined();
if (item != null)
{
//first aliases
var source_item = item.table_source_item();
if (source_item != null)
{
TableAlias tableAlias = new TableAlias();
var table_name = source_item.table_name_with_hint();
if (table_name != null)
{
var fullTableName = table_name.GetText();
if (fullTableName.Contains('.'))
{
var nameParts = fullTableName.Split('.').ToList();
for (int i = 0; i <nameParts.Count; i++)
{
tableAlias.AddParts(nameParts);
}
}
else
{
tableAlias.AddParts(fullTableName);
}
}
var table_alias = source_item.as_table_alias();
if (table_alias != null)
{
tableAlias.Alias = table_alias.GetText();
}
JoinAnalysis.Aliases.Add(tableAlias);
}
var join_parts = item.join_part();
foreach (var join_part in join_parts)
{
var table_source_joins = join_part.table_source();
if (table_source_joins != null)
{
//The join table and alias
var table_source_item_joined = table_source_joins.table_source_item_joined();
if (table_source_item_joined != null)
{
var joinAlias = new TableAlias();
var table_source_item = table_source_item_joined.table_source_item();
var table_name = table_source_item.table_name_with_hint();
if (table_name != null)
{
var fullTableName = table_name.GetText();
if (fullTableName.Contains('.'))
{
var nameParts = fullTableName.Split('.').ToList();
joinAlias.AddParts(nameParts);
}
else
{
joinAlias.AddParts(fullTableName);
}
}
if (table_source_item != null)
{
var table_alias = table_source_item.as_table_alias();
if (table_alias != null)
{
joinAlias.Alias = table_alias.GetText();
}
}
if (joinAlias.Alias != null)
{
JoinAnalysis.Aliases.Add(joinAlias);
}
}
}
var search_condition = join_part.search_condition();
if (search_condition != null)
{
//The join conditions
var conditions = search_condition.search_condition_and();
if (conditions != null)
{
foreach (var condition in conditions)
{
if (condition != null)
{
foreach (var search_condition_not in condition.search_condition_not())
{
JoinCondition joinCondition = new JoinCondition();
joinCondition.LineNumber = search_condition_not.Start.Line;
var conditionText = search_condition_not.GetText();
joinCondition.JoinConditionText = conditionText;
var splitCondition = conditionText.Split("=");
if (splitCondition.Length == 2)
{
joinCondition.LeftPart = splitCondition[0];
joinCondition.RightPart = splitCondition[1];
}
JoinAnalysis.JoinConditions.Add(joinCondition);
}
}
}
}
}
}
}
}
}
Is there a better way to do this using all of the other listener methods that have been generated without manually descending into child nodes? I there some magic that I'm missing that holds context between nodes as they are walked?
Instead of manually drilling down to sub elements in a rule you can simply listen to the the enter/exit calls for these subrules. As an example: you listen to table_sources and descent to table_source_item_joined from there to table_name_with_hint. Instead you could simply override the EnterTable_name_with_hint method.
It is totally ok to write a listener, which only handles very specific parts of the language. Look at this (C++) code in MySQL Workbench, where I created several listeners, each just handling a subpart of a larger construct or individual objects. There are listeners for create table, alter table, column definitions, triggers and more.

Unity3D: How to go Back or Forward in Array list

I have a gameObject with an ID, the gameObjects are spawned by giving initial ID: 1 , then any after spawned will be +1 so next is ID: 2.
I have two buttons that check current gameObjects ID#, BackOneButton (-1) and PlusOneButton (+1).
Currently it works but only if the array of gameObjects have IDs in order like for example [gameObject-ID:1], [gameObject-ID:2], [gameObject-ID:3]
But since you can self destruct a certain gameObject, here is where the error is --->
Now the array is not in order for example [gameObject-ID:1], [gameObject-ID:3], [gameObject-ID:4]. So if I'm currently in [gameObject-ID:3] and I use the BackOneButton and looks for ID: 2 it won't find it BUT there is ID:1. That's my error, I can't seem to figure out how to handle this.
Basically, How do I handle missing increments and skip over the missing?
Left Button (MinusOneButton)
void ButtonAction_LeftMinusOne()
{
// Get list of all gameObjects and -1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
case "1":
// nothing to go back to, this is ID: 1
break;
default:
// currently in (ID: 2 & Up) second object
int currentID = int.Parse(idObjNumber);
string idBackOne = (currentID - 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idBackOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
Right Button (PlusOneButton)
void ButtonAction_RightPlusOne()
{
// Get list of all objects and +1 current to switch
string objName = manager.currentObjectTransform.name;
string[] splitArray = objName.Split('_');
string idObjNumber = splitArray[1];
switch (idObjNumber)
{
case "0":
// not supposed to be ID: 0
break;
default:
// currently in (ID: 1 & Up) object
int currentID = int.Parse(idObjNumber);
string idPlusOne = (currentID + 1).ToString();
GameObject[] allObjInFull = GameObject.FindGameObjectsWithTag("Object");
if (allObjInFull.Length >= 2)
{
for (int i = 0; i < allObjInFull.Length; i++)
{
if (allObjInFull[i].transform.name.Contains(idPlusOne))
{
// Set Camera
camera.transform.parent = allObjInFull[i].transform.GetChild(0).GetChild(1);
camera.transform.position = allObjInFull[i].transform.GetChild(0).GetChild(1).position;
camera.transform.rotation = allObjInFull[i].transform.GetChild(0).GetChild(1).rotation;
}
}
}
break;
}
}
It would be way better (especially regarding maintenance) and more efficient to have a central manager class with a List<GameObject> where you simply Add and Remove items dynamically. (Since you already seem to have one in manager I would rather extend that one)
public static class ObjectsManager
{
// If you are not concerned about
// capsulation you could ofcourse make this public as well
// but I thought this is cleaner
private static List<GameObject> objects;
// Read-only property
public static int Count
{
get
{
Initialize();
return objects.Count;
}
}
// initialize the list once
// I first had this in e.g. Awake
// but now you can easily use this in multiple scenes
public static void Initialize(bool force reinitialize = false)
{
if(objects != null && ! reinitialize) return;
objects = FindObjectsWithTag("Object").ToList();
}
public static void Add(GameObject newObject)
{
Initialize();
if(objects.Contains(newObject) return;
objects.Add(newObject);
}
public static void Destroy(GameObject toDestroy)
{
Initialize();
if(objects.Contains(toDestroy)
{
objects.Remove(toDestroy);
}
Object.Destroy(toDestroy);
}
public static int IndexOf(GameObject obj)
{
Initialize();
return objects.IndexOf(obj);
}
public static GameObject GetByIndex(int index)
{
Initialize();
// Use modulo to wrap around the index in case
// +1 or -1 exceeds the list ends
// in your case you might not need it
// but I decided to add it to be more flexible
var nextIndex = (index + 1) % objects.Count;
return objects[index];
}
}
Everytime you Instantiate a new object make sure to also call
ObjectsManager.Add(newObject);
and everytime where you destroy an object rather use
ObjectsManager.Destroy(objectToDestroy);
so it is also removed from the list first.
Then you can easily use
var currentIndex = ObjectsManager.IndexOf(certainObject);
to get the current index of an object and simply move through the index (+1, -1)
var nextObject = ObjectsManager.GetByIndex(currentIndex + 1);
var lastObject = Objects manager.GetByIndex(currentIndex - 1);
In case you switch the scene you have reinitialize the list once in order to get rid of null references
ObjectsManager.Initialize(true);
In your example code you would e.g. use something like
void ButtonAction_LeftMinusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == 0)
{
// nothing to do go back to
// Except you want wrap around then simply remove this check
Debug.Log("Already is first object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex - 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}
And accordingly
void ButtonAction_RightPlusOne()
{
GameObject currentObject = manager.currentObjectTransform.gameObject;
int currentIndex = ObjectsManager.IndexOf(currentObject);
if(currentIndex < 0)
{
Debug.LogErrorFormat(this, "Object {0} is not in list!", currentObject.name);
return;
}
if(currentIndex == ObjectsManager.Count - 1)
{
// nothing to do go forward to
// Except you want wrap around then simply remove this check
Debug.Log("Already is last object in list", this);
return;
}
GameObject newObject = ObjectsManager.GetByIndex(currentIndex + 1);
Transform childOfNewObject = newObject.GetChild(0).GetChild(1);
// Set Camera
// Using simply SetParent with parameter worldPositionStays=false
// reduces it to one single call
camera.transform.SetParent( childOfNewObject, false);
}

Use Kinect to create a digital catalog application

I am creating a WPF application to create digital catalog using kinect v1.8. I am trying to track only a single skeleton using following code:-
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs skeletonFrameReadyEventArgs)
{
// Even though we un-register all our event handlers when the sensor
// changes, there may still be an event for the old sensor in the queue
// due to the way the KinectSensor delivers events. So check again here.
if (this.KinectSensor != sender)
{
return;
}
SkeletonFrame skeletonFrame = skeletonFrameReadyEventArgs.OpenSkeletonFrame();
if (skeletonFrame == null)
return;
Skeleton[] skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
Skeleton skeleton = (from skl in skeletons
where skl.TrackingState == SkeletonTrackingState.Tracked
select skl).FirstOrDefault();
if (skeleton == null)
return;
Skeleton[] s = new Skeleton[1];
s[0] = skeleton;
if (SkeletonTrackingState.Tracked == s[0].TrackingState)
{
//s1.SkeletonStream.ChooseSkeletons(s[0].TrackingId);
var accelerometerReading = this.KinectSensor.AccelerometerGetCurrentReading();
this.interactionStream.ProcessSkeleton(s, accelerometerReading, skeletonFrame.Timestamp);
}
}
I am getting an exception when I run the code and skeleton gets detected as follows:-
on the line "this.interactionStream.ProcessSkeleton(s, accelerometerReading, skeletonFrame.Timestamp);"
I need to detect only one skeleton and use it for further processing like to access the digital catalog applications.
Thanks in advance.
I have Faced Same Problem By using below code I have track only one skeleton Which is closer to the sensor.and directly assign the closest skeleton to the main skeleton stream.
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs skeletonFrameReadyEventArgs)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = skeletonFrameReadyEventArgs.OpenSkeletonFrame())
{
if (skeletonFrame != null && this.skeletons != null)
{
//Console.WriteLine(skeletonFrame.SkeletonArrayLength);
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
// Set skeleton datas from skeletonFrame
skeletonFrame.CopySkeletonDataTo(this.skeletons);
TrackClosestSkeleton();
Skeleton[] singleSkeleton = new Skeleton[6];
Skeleton skl=(from mno in this.skeletons where mno.TrackingState==SkeletonTrackingState.Tracked && mno.TrackingId==globalClosestID select mno).FirstOrDefault();
if (skl == null)
return;
//Creating an empty skkeleton
Skeleton emptySkeleton = new Skeleton();
singleSkeleton[0] = skl; //Pass the Tracked skeleton with closestID
singleSkeleton[1] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[2] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[3] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[4] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[5] = emptySkeleton; //Passing Empty Skeleton
this.snew.SkeletonStream.ChooseSkeletons(globalClosestID);
var accelerometerReading = this.KinectSensor.AccelerometerGetCurrentReading();
this.interactionStream.ProcessSkeleton(singleSkeleton, accelerometerReading, skeletonFrame.Timestamp);
}
}
}
int globalClosestID = 0;
private void TrackClosestSkeleton()
{
if (this.snew != null && this.snew.SkeletonStream != null)
{
if (!this.snew.SkeletonStream.AppChoosesSkeletons)
{
this.snew.SkeletonStream.AppChoosesSkeletons = true; // Ensure AppChoosesSkeletons is set
}
float closestDistance = 10000f; // Start with a far enough distance
int closestID = 0;
foreach (Skeleton skeleton in this.skeletons.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked))
{
if (skeleton.Position.Z < closestDistance)
{
closestID = skeleton.TrackingId;
closestDistance = skeleton.Position.Z;
}
}
if (closestID > 0)
{
this.snew.SkeletonStream.ChooseSkeletons(closestID); // Track this skeleton
globalClosestID = closestID;
}
}
}
check the above code it works for me.It may helpful to you.Here snew is the Kinectsensor.
You should try to track the closest skeleton using this method from MSDN
private void TrackClosestSkeleton()
{
if (this.kinect != null && this.kinect.SkeletonStream != null)
{
if (!this.kinect.SkeletonStream.AppChoosesSkeletons)
{
this.kinect.SkeletonStream.AppChoosesSkeletons = true; // Ensure AppChoosesSkeletons is set
}
float closestDistance = 10000f; // Start with a far enough distance
int closestID = 0;
foreach (Skeleton skeleton in this.skeletonData.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked))
{
if (skeleton.Position.Z < closestDistance)
{
closestID = skeleton.TrackingId;
closestDistance = skeleton.Position.Z;
}
}
if (closestID > 0)
{
this.kinect.SkeletonStream.ChooseSkeletons(closestID); // Track this skeleton
}
}
}
And then in your SkeletonFrameReady
private void SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null && this.skeletonData != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
// Set skeleton datas from skeletonFrame
skeletonFrame.CopySkeletonDataTo(this.skeletonData);
TrackClosestSkeleton();
}
}
//Do some stuff here
}

Error in convert inventory from JS to C# - Unity

Hello :) I'm converting now Inventory system but i'm stuck on List / Arrays (JS).
Here's my script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu ("Inventory/Character Sheet")]
[RequireComponent(typeof (Inventory))]
public class Character : MonoBehaviour {
//The Character window (CSheet).
public Transform WeaponSlot; //This is where the Weapons are going to go (be parented too). In my case it's the "Melee" gameobject.
//private Item[] ArmorSlot;
private List<Item> ArmorSlot; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script.
//public string[] ArmorSlotName;
public List<string> ArmorSlotName; //This determines how many slots the character has (Head, Legs, Weapon and so on) and the text on each slot.
//public Rect[] buttonPositions;
public List<Rect> buttonPositions; //This list will contain where all buttons, equipped or not will be and SHOULD HAVE THE SAME NUMBER OF cells as the ArmorSlot array.
Vector2 windowSize = new Vector2(375,300); //The size of the character window.
public bool useCustomPosition = false; //Do we want to use the customPosition variable to define where on the screen the Character window will appear.
Vector2 customPosition = new Vector2 (70, 70); //The custom position of the Character window.
public GUISkin cSheetSkin; //This is where you can add a custom GUI skin or use the one included (CSheetSkin) under the Resources folder.
public bool canBeDragged = true; //Can the Character window be dragged?
public KeyCode onOffButton = KeyCode.I; //The key to toggle the Character window on and of.
bool DebugMode = false; //If this is enabled, debug.logs will print out information when something happens (equipping items etc.).
static bool csheet = false; //Helps with turning the CharacterSheet on and off.
private Rect windowRect = new Rect(100,100,200,300); //Keeping track of our character window.
//These are keeping track of components such as equipmentEffects and Audio.
private Inventory playersinv; //Refers to the Inventory script.
private bool equipmentEffectIs = false;
private InvAudio invAudio;
private bool invDispKeyIsSame = false;
//Assign the differnet components to variables and other "behind the scenes" stuff.
void Awake ()
{
playersinv = GetComponent<Inventory>();
if (useCustomPosition == false)
{
windowRect = new Rect(Screen.width-windowSize.x-70,Screen.height-windowSize.y-(162.5f+70*2),windowSize.x,windowSize.y);
}
else
{
windowRect = new Rect(customPosition.x,customPosition.y,windowSize.x,windowSize.y);
}
invAudio = GetComponent<InvAudio>();
if (GetComponent<InventoryDisplay>().onOffButton == onOffButton)
{
invDispKeyIsSame = true;
}
}
//Take care of the array lengths.
void Start ()
{
ArmorSlot = new Item[ArmorSlotName.Count];
if (buttonPositions.Count != ArmorSlotName.Count)
{
Debug.LogError("The variables on the Character script attached to " + transform.name + " are not set up correctly. There needs to be an equal amount of slots on 'ArmorSlotName' and 'buttonPositions'.");
}
}
//Checking if we already have somthing equipped
bool CheckSlot(int tocheck)
{
bool toreturn = false;
if(ArmorSlot[tocheck]!=null){
toreturn=true;
}
return toreturn;
}
//Using the item. If we assign a slot, we already know where to equip it.
public void UseItem(Item i, int slot, bool autoequip)
{
if(i.isEquipment){
//This is in case we dbl click the item, it will auto equip it. REMEMBER TO MAKE THE ITEM TYPE AND THE SLOT YOU WANT IT TO BE EQUIPPED TO HAVE THE SAME NAME.
if(autoequip)
{
int index = 0; //Keeping track of where we are in the list.
int equipto = 0; //Keeping track of where we want to be.
foreach(string a in ArmorSlotName) //Loop through all the named slots on the armorslots list
{
if(a == i.itemType) //if the name is the same as the armor type.
{
equipto=index; //We aim for that slot.
}
index++; //We move on to the next slot.
}
EquipItem(i,equipto);
}
else //If we dont auto equip it then it means we must of tried to equip it to a slot so we make sure the item can be equipped to that slot.
{
if(i.itemType==ArmorSlotName[slot]) //If types match.
{
EquipItem(i,slot); //Equip the item to the slot.
}
}
}
if (DebugMode)
{
Debug.Log(i.name + " has been used");
}
}
//Equip an item to a slot.
void EquipItem(Item i, int slot)
{
if(i.itemType == ArmorSlotName[slot]) //If the item can be equipped there:
{
if(CheckSlot(slot)) //If theres an item equipped to that slot we unequip it first:
{
UnequipItem(ArmorSlot[slot]);
ArmorSlot[slot]=null;
}
ArmorSlot[slot]=i; //When we find the slot we set it to the item.
gameObject.SendMessage ("PlayEquipSound", SendMessageOptions.DontRequireReceiver); //Play sound
//We tell the Item to handle EquipmentEffects (if any).
if (i.GetComponent<EquipmentEffect>() != null)
{
equipmentEffectIs = true;
i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
}
//If the item is also a weapon we call the PlaceWeapon function.
if (i.isAlsoWeapon == true)
{
if (i.equippedWeaponVersion != null)
{
PlaceWeapon(i);
}
else
{
Debug.LogError("Remember to assign the equip weapon variable!");
}
}
if (DebugMode)
{
Debug.Log(i.name + " has been equipped");
}
playersinv.RemoveItem(i.transform); //We remove the item from the inventory
}
}
//Unequip an item.
void UnequipItem(Item i)
{
gameObject.SendMessage ("PlayPickUpSound", SendMessageOptions.DontRequireReceiver); //Play sound
//We tell the Item to disable EquipmentEffects (if any).
if (i.equipmentEffect != null)
{
equipmentEffectIs = false;
i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
}
//If it's a weapon we call the RemoveWeapon function.
if (i.itemType == "Weapon")
{
RemoveWeapon(i);
}
if (DebugMode)
{
Debug.Log(i.name + " has been unequipped");
}
playersinv.AddItem(i.transform);
}
//Places the weapon in the hand of the Player.
void PlaceWeapon (Item item)
{
GameObject Clone = GameObject.Instantiate(item.equippedWeaponVersion, WeaponSlot.position, WeaponSlot.rotation) as GameObject;
Clone.name = item.equippedWeaponVersion.name;
Clone.transform.parent = WeaponSlot;
if (DebugMode)
{
Debug.Log(item.name + " has been placed as weapon");
}
}
//Removes the weapon from the hand of the Player.
void RemoveWeapon (Item item)
{ if (item.equippedWeaponVersion != null)
{
Destroy(WeaponSlot.FindChild("" + item.equippedWeaponVersion.name).gameObject);
if (DebugMode)
{
Debug.Log(item.name + " has been removed as weapon");
}
}
}
void Update ()
{
//This will turn the character sheet on and off.
if (Input.GetKeyDown(onOffButton))
{
if (csheet)
{
csheet = false;
if (invDispKeyIsSame != true)
{
gameObject.SendMessage ("ChangedState", false, SendMessageOptions.DontRequireReceiver); //Play sound
gameObject.SendMessage("PauseGame", false, SendMessageOptions.DontRequireReceiver); //StopPauseGame/EnableMouse/ShowMouse
}
}
else
{
csheet = true;
if (invDispKeyIsSame != true)
{
gameObject.SendMessage ("ChangedState", true, SendMessageOptions.DontRequireReceiver); //Play sound
gameObject.SendMessage("PauseGame", true, SendMessageOptions.DontRequireReceiver); //PauseGame/DisableMouse/HideMouse
}
}
}
}
//Draw the Character Window
void OnGUI()
{
GUI.skin = cSheetSkin; //Use the cSheetSkin variable.
if(csheet) //If the csheet is opened up.
{
//Make a window that shows what's in the csheet called "Character" and update the position and size variables from the window variables.
windowRect = GUI.Window (1, windowRect, DisplayCSheetWindow, "Character");
}
}
//This will display the character sheet and handle the buttons.
void DisplayCSheetWindow(int windowID)
{
if (canBeDragged == true)
{
GUI.DragWindow (new Rect (0,0, 10000, 30)); //The window is dragable.
}
int index = 0;
foreach(Item a in ArmorSlot) //Loop through the ArmorSlot array.
{
if(a == null)
{
if(GUI.Button(buttonPositions[index], ArmorSlotName[index])) //If we click this button (that has no item equipped):
{
InventoryDisplay id = GetComponent<InventoryDisplay>();
if(id.itemBeingDragged != null) //If we are dragging an item:
{
EquipItem(id.itemBeingDragged,index); //Equip the Item.
id.ClearDraggedItem();//Stop dragging the item.
}
}
}
else
{
if(GUI.Button(buttonPositions[index],ArmorSlot[index].itemIcon)) //If we click this button (that has an item equipped):
{
InventoryDisplay id2 = GetComponent<InventoryDisplay>();
if(id2.itemBeingDragged != null) //If we are dragging an item:
{
EquipItem(id2.itemBeingDragged,index); //Equip the Item.
id2.ClearDraggedItem(); //Stop dragging the item.
}
else if (playersinv.Contents.Count < playersinv.MaxContent) //If there is room in the inventory:
{
UnequipItem(ArmorSlot[index]); //Unequip the Item.
ArmorSlot[index] = null; //Clear the slot.
id2.ClearDraggedItem(); //Stop dragging the Item.
}
else if (DebugMode)
{
Debug.Log("Could not unequip " + ArmorSlot[index].name + " since the inventory is full");
}
}
}
index++;
}
}
}
And I have this error:
Assets/Inventory/Scripts/Character.cs(62,17): error CS0029: Cannot implicitly convert type Item[]' toSystem.Collections.Generic.List'
this lane:
ArmorSlot = new Item[ArmorSlotName.Count];
in JS version there were arrays but in c# i convert it to Lists and i have couple of errors ;D Can someone help me with this ? ;/
Error happens over here.
ArmorSlot = new Item[ArmorSlotName.Count];
What is ArmorSlot?
Private List<Item> ArmorSlot; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script.
you don't make List like normal array.
You don't want List you want Item array.
Fix is like this
private Item[] ArmorSlot;
But maybe you want List because list is easier to control then a native C# array if you wan't to use List you must do something like this
ArmorSlot = new ArrayList<Item>(ArmorSlotName.Count);
But maybe you don't need to put in ArmorSlotName.Count because List is the size of how much items you put inside it.. it gives default size and keeps increasing.
So it's better to just do this
ArmorSlot = new ArrayList<Item>();

Giving SelectedIndex -1 in Listbox

I'm having listbox and getting selected item. The code is
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int index = listBox1.SelectedIndex;
string str ="";
if (index == 0)
{
str = (string)Text1.Text;
}
else if (index == 1)
{
str = (string)Text2.Text;
}
else if (index == 2)
{
str = (string)Text3.Text;
}
MessageBox.Show(str);
// listBox1.SelectedIndex = -1;
}
By this above code, after I selected one item,blue color bar is displaying in selected item, to avoid that I gave listBox1.SelectedIndex = -1;.
If I gave this this function is get executed twice.and the message box shows empty string.
Why is it happening? How can I avoid that?
try construction like this:
listBox1.SelectionChanged -= listBox1_SelectionChanged;
listBox1.SelectedIndex = -1;
listBox1.SelectionChanged += listBox1_SelectionChanged;
listBox1.SelectedIndex is calling SelectionChanged event so this function is called twice.

Resources